乐闻世界logo
搜索文章和话题

Axios 如何正确处理数组类型的参数?

7 个月前提问
3 个月前修改
浏览次数125

6个答案

1
2
3
4
5
6

当我们在使用 Axios 进行API调用时,可能需要向服务器发送数组类型的参数。正确处理数组类型的参数依赖于服务器端如何解析参数。一般来说,有几种方式可以提交数组类型的参数:

1. 通过查询字符串传递数组

你可以将数组转换为查询字符串的形式,例如:

shell
GET /endpoint?param[]=value1&param[]=value2

在 Axios 中,你可以简单地将数组直接作为参数传递,Axios 会自动将其序列化为查询字符串:

javascript
axios.get('/endpoint', { params: { param: ['value1', 'value2'] } });

Axios 会将请求转换为 /endpoint?param=value1&param=value2

2. 使用 paramsSerializer 自定义序列化

如果你需要自定义数组转为查询字符串的方式,可以使用 paramsSerializer 函数。例如,你可能想要使用逗号分隔数组:

javascript
import qs from 'qs'; // 使用 qs 库进行查询字符串的序列化 axios.get('/endpoint', { params: { param: ['value1', 'value2'] }, paramsSerializer: params => { return qs.stringify(params, { arrayFormat: 'comma' }) } });

这会将请求转换为 /endpoint?param=value1,value2

3. 在 POST 请求中发送数组作为 JSON

如果你是在发送 POST 请求,并且需要在请求体中发送数组,你可以将数组作为 JSON 对象发送:

javascript
axios.post('/endpoint', { arrayParam: ['value1', 'value2'] });

这样,数组会作为 JSON 的一部分发送到服务器。

例子

假设有一个API端点 /search 需要接收一个数组类型的参数 tags 来过滤搜索结果。按照查询字符串的方式,我们可以这样调用 API:

javascript
axios.get('/search', { params: { tags: ['frontend', 'javascript', 'react'] } });

如果服务器期望的是逗号分隔的字符串而不是多个相同的键,我们可以用 paramsSerializer 自定义序列化方法:

javascript
import qs from 'qs'; axios.get('/search', { params: { tags: ['frontend', 'javascript', 'react'] }, paramsSerializer: params => { return qs.stringify(params, { arrayFormat: 'comma' }); } });

上述方法都是处理发送数组类型参数时的常见方式,具体使用哪种方法取决于后端API的预期格式,所以在实际应用中,应当根据服务器端的要求来选择合适的数组序列化方式。

2024年6月29日 12:07 回复

You can use paramsSerializer and serialize parameters with https://www.npmjs.com/package/qs

shell
axios.get('/myController/myAction', { params: { storeIds: [1,2,3] }, paramsSerializer: params => { return qs.stringify(params) } })
2024年6月29日 12:07 回复

Without having to add more libraries and using ES6 you could write:

shell
axios.get(`/myController/myAction?${[1,2,3].map((n, index) => `storeIds[${index}]=${n}`).join('&')}`);
2024年6月29日 12:07 回复

Thanks so much the answer from Nicu Criste, for my case, the API requires params like this:

shell
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:

shell
config.paramsSerializer = p => { return qs.stringify(p, {arrayFormat: 'brackets'}) }
2024年6月29日 12:07 回复

This behaviour has been added to axios starting with version 1.0.0. See paramsSerializer.indexes at https://github.com/axios/axios/tree/v1.0.0#request-config

Here's an example using your sample code:

shell
axios.get('/myController/myAction', { params: { storeIds: [1,2,3] }, paramsSerializer: { indexes: true, // use brackets with indexes } )

The resulting query params will have indexes inside the brackets:

shell
/myController/myAction?storeIds[0]=1&storeIds[1]=2&storeIds[2]=3

Other paramsSerializer.indexes values are null (no brackets):

shell
axios.get('/myController/myAction', { params: { storeIds: [1,2,3] }, paramsSerializer: { indexes: null, // no brackets at all } ) // /myController/myAction?storeIds=1&storeIds=2&storeIds=3

And the default false (brackets without indexes):

shell
axios.get('/myController/myAction', { params: { storeIds: [1,2,3] }, paramsSerializer: { indexes: false, // brackets but no indexes } ) // /myController/myAction?storeIds[]=1&storeIds[]=2&storeIds[]=3
2024年6月29日 12:07 回复

In my case, I use ES6 array function. array element make querystring use reduce function. Object array also works.

shell
const storeIds = [1,2,3] axios.get('some url', { params: { storeIds: storeIds.reduce((f, s) => `${f},${s}`) } })
2024年6月29日 12:07 回复

你的答案