Javascript 如何在数组中正确使用 axios 参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/49944387/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to correctly use axios params with arrays
提问by Zin Kun
How to add indexes to array in query string?
如何在查询字符串中向数组添加索引?
I tried send data like this:
我尝试发送这样的数据:
axios.get('/myController/myAction', { params: { storeIds: [1,2,3] })
And I got this url:
我得到了这个网址:
http://localhost/api/myController/myAction?storeIds[]=1&storeIds[]=2&storeIds[]=3
So, I should to get this url:
所以,我应该得到这个网址:
http://localhost/api/myController/myAction?storeIds[0]=1&storeIds[1]=2&storeIds[2]=3
What I should add in my params options to get this url?
我应该在我的 params 选项中添加什么来获取这个 url?
回答by Nicu Criste
You can use paramsSerializerand serialize parameters with https://www.npmjs.com/package/qs
您可以paramsSerializer通过https://www.npmjs.com/package/qs使用和序列化参数
axios.get('/myController/myAction', {
  params: {
    storeIds: [1,2,3]
  },
  paramsSerializer: params => {
    return qs.stringify(params)
  }
})
回答by Jorge
This was better for me:
这对我来说更好:
axios.get('/myController/myAction', {
params: { storeIds: [1,2,3] + ''}
})
})
回答by Heo ??t Hades
Thanks so much the answer from Nicu Criste, for my case, the API requires params like this:
非常感谢Nicu Criste的回答,就我而言,API 需要这样的参数:
params: {
  f: {
    key: 'abc',
    categories: ['a','b','c']
   },
  per_page: 10
}
Method is GET and this API requires the format is: API?f[key]=abc&f[categories][]=a&f[categories][]=b...So I assigned the paramsSerializer of axios like this:
方法是GET,这个API要求的格式是:API?f[key]=abc&f[categories][]=a&f[categories][]=b...所以我这样分配了axios的paramsSerializer:
config.paramsSerializer = p => {
      return qs.stringify(p, {arrayFormat: 'brackets'})
    }
- Install 
qsplease go to this link - Read more about paramsSerializer in axios document
 - Edit format of params: Read more at qs stringifying document
 
- 安装
qs请转到此链接 - 在axios 文档中阅读有关 paramsSerializer 的更多信息
 - 参数的编辑格式:在qs stringifying 文档中阅读更多信息
 
回答by ???
In my case, I use ES6 array function. array element make querystring use reduce function. Object array also works.
就我而言,我使用 ES6 数组函数。数组元素使查询字符串使用reduce 函数。对象数组也有效。
const storeIds = [1,2,3]
axios.get('some url', {
  params: {
    storeIds: storeIds.reduce((f, s) => `${f},${s}`)
  }
})
回答by Bastin Robin
In my case, there was already jQuery implemented into my codebase. So I just used the predefined method.
就我而言,我的代码库中已经实现了 jQuery。所以我只是使用了预定义的方法。
jQuery.param(Object)

