Passing an object with a parameter with multiple values as a query string in a GET using axios

我的未来我决定 提交于 2019-12-11 09:19:28

问题


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.



来源:https://stackoverflow.com/questions/42102575/passing-an-object-with-a-parameter-with-multiple-values-as-a-query-string-in-a-g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!