Passing an object with a parameter with multiple v

2019-07-24 15:18发布

问题:

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?

回答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.