查询参数(axios请求)中具有相同键的多个字段?

Mar*_*nen 23 javascript parameters request axios

所以后端(不在我的控制之下)需要一个像这样的查询字符串:

http://example.com/?foo=5&foo=2&foo=11
Run Code Online (Sandbox Code Playgroud)

但是axios使用JS对象发送请求参数:

axios.get('http://example.com/', { foo: 5 });
Run Code Online (Sandbox Code Playgroud)

显然,这样的对象不能有多个具有相同键的字段.

如何使用相同的密钥发送包含多个字段的请求?

小智 37

请求配置上的axios文档

// `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
params: {
  ID: 12345
},
Run Code Online (Sandbox Code Playgroud)

要在请求中使用它,您可以这样做

var request = {
  params: {
    foo: [5, 2, 11]
  }
}
axios.get('http://example.com/', request);
Run Code Online (Sandbox Code Playgroud)

使用普通对象方法的唯一问题是数组参数被添加为

http://example.com/?foo[]=5&foo[]=2&foo[]=11
Run Code Online (Sandbox Code Playgroud)

要获得没有[]您想要的请求,您可以使用URLSearchParams

var params = new URLSearchParams();
params.append("foo", 5);
params.append("foo", 2);
params.append("foo", 11);
var request = {
  params: params
};
axios.get('http://example.com/', request);
Run Code Online (Sandbox Code Playgroud)

这将导致请求为

http://example.com/?foo=5&foo=2&foo=11
Run Code Online (Sandbox Code Playgroud)


小智 20

在Axios请求配置中,您可以覆盖params序列化,然后使用QS NPM模块重复模式序列化阵列

let params = { foo: [5, 2] }

axios.get('path/to/api/',{params}) // URL : https://path/to/api?foo[]=5&foo[]=2

let myAxios = axios.create({
    paramsSerializer: params => Qs.stringify(params, {arrayFormat: 'repeat'})
})
myAxios.get('path/to/api/',{params}) // URL : https://path/to/api?foo=5&foo=2
Run Code Online (Sandbox Code Playgroud)

  • 我使用了“query-string”模块,其工作原理类似,但没有“repeat”选项,而是默认执行相同的行为。 (2认同)

dan*_*r89 17

最新 axios 版本(2022 年)的正确答案是设置indexes: null以获得arrayFormat: 'repeat'.

更多信息:https://github.com/axios/axios/issues/5058#issuecomment-1272107602

例子:

const {data} = await axios.get('https://postman-echo.com/get', {
  params: {
    a: ['b', 'c', 'd']
  },
  paramsSerializer: {
    indexes: null // by default: false
  }
});
Run Code Online (Sandbox Code Playgroud)

qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) ==> config.paramsSerializer.indexes = true // 'a[0]=b&a[1]=c '

qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) ==> config.paramsSerializer.indexes = false// 'a[]=b&a[]=c' / /默认

qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) ==> config.paramsSerializer.indexes = null// 'a=b&a=c'

qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' }) ==>不支持// 'a=b,c'