Axios adds square brackets to the param if there are multiple params with an equal name. The problem is that I need not to include those brackets since I use Django Rest Framework
and Django Filters
.
How can I do that if I use this notation?
axios.get(list_url, {params: {somelist:[1,2,3]}})
I don't want url/?somelist[]=1&somelist[]=2&somelist[]=3
Instead I want url/?somelist=1&somelist=2&somelist=3
Axios adds square brackets to the param if there are multiple params with an equal name. The problem is that I need not to include those brackets since I use Django Rest Framework
and Django Filters
.
How can I do that if I use this notation?
axios.get(list_url, {params: {somelist:[1,2,3]}})
I don't want url/?somelist[]=1&somelist[]=2&somelist[]=3
Instead I want url/?somelist=1&somelist=2&somelist=3
3 Answers
Reset to default 5Try to do it using paramsSerializer's indexes:null
in axios config
axios.get(someurl, {
params: {
foo: [1, 2, 3]
},
paramsSerializer: {
indexes: null
}
});
I got this from here https://www.npmjs./package/axios#axios-api
screenshot with attributes of paramsSerializer
You can do like this with URLSearchParams
(a native object that exists in browsers and in Node.js as well):
const axios = require('axios');
const { URLSearchParams } = require('url');
var params = new URLSearchParams();
params.append("q", 'test');
params.append("foo", 2);
params.append("foo", 11);
var request = {
params: params
};
axios.get('http://google./', request).then(x => x.request).then(console.log);
If you look at the RequestConfig object in axios documentation, there's a paramsSerializer
function whose default value uses the stringify
function of the qs package in this way:
// `paramsSerializer` is an optional function in charge of serializing `params`
// (e.g. https://www.npmjs./package/qs, http://api.jquery./jquery.param/)
paramsSerializer: function (params) {
return qs.stringify(params, {arrayFormat: 'brackets'})
},
If you want to keep the qs package, you may use the arrayFormat
option to specify the format of the output array:
qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })
// 'a[0]=b&a[1]=c'
qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })
// 'a[]=b&a[]=c'
qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })
// 'a=b&a=c'
qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'ma' })
// 'a=b,c'
In your case :
axios.get(listUrl, {
params: {
someList: [1, 2, 3]
},
paramsSerializer: (params) => qs.stringify(params, {arrayFormat: 'repeat'}),
});
Or at global instance level:
const axios = axios.create({
baseURL: someBaseUrl,
paramsSerializer: (params) => qs.stringify(params, {arrayFormat: 'repeat'}),
});