4

It is common to pass a parameter with multiple values as a query string on a GET:

http://server/status?stat=a&stat=b

How does one create this type of query string using the axios library in JS? Creating an object where the parameter name is the key and the value is the array of multiple values creates a query string:

http://server/status?stat[]=a&stat[]=b

which is an incorrect format from what the server expects. Can this be done in axios?

2 Answers 2

5

If the server expects a get with multiple instances of a given name (without the [] array marker appended) that can be obtained using the URLSearchParams API.:

var searchParams = new URLSearchParams();
searchParams.append('stat', 'a')
searchParams.append('stat', 'b')
axios.get('http://server/status', {params: searchParams});

Would yield a request:

http://server/status?stat=a&stat=b

As noted in another answer it does not work in IE, but the polyfill url-search-params is available.

Sign up to request clarification or add additional context in comments.

Comments

1

It is common to pass a parameter with multiple values as a query string on a GET

This is by no means a standard. Different languages, frameworks implement different solutions. See this question on the Authoritative position of duplicate HTTP GET query keys.

Can this be done in axios?

From the Axios documentation:

In node.js, you can use the querystring module as follows:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar'});

You can also use the qs library.

The qs library has support for arrays.

An alternative would be to use Connect.

Update

The QS library supports arrays, but only if the parameter is suffixed with []:

var paramsString = "q=URLUtils.searchParams&topic[]=api&topic[]=bar"

Alternatively, the URLSearchParams API offers a getAll() method:

var paramsString = "q=URLUtils.searchParams&topic=api"
var searchParams = new URLSearchParams(paramsString);

searchParams.getAll("topic"); // ["api"]

This doesn't work in IE, but the polyfill url-search-params is available.

3 Comments

URLSearchParams API can also be used according to the Axios doc. thanks @sgtdck
I tried the qs library, but it does not currently have support for 1 to many key/value pairs (key=stat, value=1,2,3...). The URLSearchParams interface remains to be a valid solution. This API is not supported in IE, but the polyfill url-search-params is available.
@flashmatrix I updated the answer, but re-reading your comment I didn't realise you needed 1:many key/value pairs. What you mean is ?key=stat&value=1,2,3 which would result in stat = [1,2,3]?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.