对于需要发送数组数据的情况,在Axios请求中添加可选参数“paramsSerializer”,使用该参数可以将数组数据序列化为字符串格式并发送。
例如,需要发送以下数据数组:
const data = {
ids: [1, 2, 3],
name: 'John'
}
使用Axios发送POST请求时,需要添加paramsSerializer参数,将数据数组序列化为字符串格式并加入请求:
const qs = require('qs');
axios.post('/api/data', qs.stringify(data, {arrayFormat: 'repeat'}), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
paramsSerializer: (params) => {
return qs.stringify(params, { arrayFormat: 'repeat' })
}
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
在上面的示例代码中,qs.stringify()方法使用了“arrayFormat: 'repeat'”选项,该选项将数组转换为形如“ids=1&ids=2&ids=3”的字符串格式,便于发送。在Axios请求中,paramsSerializer参数中将使用qs.stringify()方法的选项将参数序列化为queryString格式并加入请求中,请求发送的数据即包括数组数据和其他普通数据。