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?

flashmatrix
  • 185
  • 1
  • 2
  • 6

2 Answers2

4

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.

Johan Lübcke
  • 19,666
  • 8
  • 38
  • 35
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.

Community
  • 1
  • 1
sgtdck
  • 1,008
  • 7
  • 15
  • URLSearchParams API can also be used according to the Axios doc. thanks @sgtdck – flashmatrix Feb 08 '17 at 18:35
  • 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](https://github.com/WebReflection/url-search-params) is available. – flashmatrix Feb 09 '17 at 23:47
  • @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]`? – sgtdck Feb 10 '17 at 00:26