So the backend (not under my control) requires a query string like this:
JavaScript
x
2
1
http://example.com/?foo=5&foo=2&foo=11
2
But axios
uses a JS object to send the request params:
JavaScript
1
2
1
axios.get('http://example.com/', { foo: 5 });
2
And obviously an object can’t have multiple fields with the same key.
How can I send a request with multiple fields with the same key?
Advertisement
Answer
From the Request Config section of the axios documentation:
JavaScript161// `params` are the URL parameters to be sent with the request
2// Must be a plain object or a URLSearchParams object
3params: {
4ID: 12345
5},
6
To use this in a request, you would do
JavaScript
1
7
1
const request = {
2
params: {
3
foo: [5, 2, 11]
4
}
5
}
6
axios.get('http://example.com/', request);
7
The issue with using a plain object is that array parameters are added as
JavaScript
1
2
1
http://example.com/?foo[]=5&foo[]=2&foo[]=11
2
To make a request to a URL without the []
, use URLSearchParams
JavaScript
1
9
1
var params = new URLSearchParams();
2
params.append("foo", 5);
3
params.append("foo", 2);
4
params.append("foo", 11);
5
var request = {
6
params: params
7
};
8
axios.get('http://example.com/', request);
9
This will result in a request to
JavaScript
1
2
1
http://example.com/?foo=5&foo=2&foo=11
2