Javascript 查询参数中具有相同键的多个字段(axios 请求)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42898009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:30:19  来源:igfitidea点击:

Multiple fields with same key in query params (axios request)?

javascriptparametersrequestaxios

提问by Markus Meskanen

So the backend (not under my control) requires a query string like this:

所以后端(不在我的控制之下)需要一个这样的查询字符串:

http://example.com/?foo=5&foo=2&foo=11

But axiosuses JS object to send the request params:

但是axios使用 JS 对象发送请求参数:

axios.get('http://example.com/', { foo: 5 });

And obviously such object can't have multiple fields with the same key.

很明显,这样的对象不能有多个具有相同键的字段。

How can I send a request with multiple fields with same key?

如何使用相同的键发送包含多个字段的请求?

回答by nhydock

From the axios documentation on the request config

来自请求配置的 axios 文档

// `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
params: {
  ID: 12345
},

To use this in a request, you would do

要在请求中使用它,你会这样做

var request = {
  params: {
    foo: [5, 2, 11]
  }
}
axios.get('http://example.com/', request);

The only issue with using a plain object approach is that array parameters are added as

使用普通对象方法的唯一问题是数组参数添加为

http://example.com/?foo[]=5&foo[]=2&foo[]=11

To get request without the []like you want, you can use the URLSearchParams

要获得没有[]你想要的请求,你可以使用 URLSearchParams

var params = new URLSearchParams();
params.append("foo", 5);
params.append("foo", 2);
params.append("foo", 11);
var request = {
  params: params
};
axios.get('http://example.com/', request);

This will result in a request as

这将导致请求为

http://example.com/?foo=5&foo=2&foo=11

回答by Ashwin Kumar

In Axios request config, you can override params serialization and then use QS NPM moduleto serialize array with repeatmode

在 Axios 请求配置中,您可以覆盖 params 序列化,然后使用QS NPM 模块重复模式序列化数组

let params = { foo: [5, 2] }

axios.get('path/to/api/',{params}) // URL : https://path/to/api?foo[]=5&foo[]=2

let myAxios = axios.create({
    paramsSerializer: params => Qs.stringify(params, {arrayFormat: 'repeat'})
})
myAxios.get('path/to/api/',{params}) // URL : https://path/to/api?foo=5&foo=2

回答by Yash Agrawal

Adding more details to @nhydock accepted answer. When you do

向@nhydock 接受的答案添加更多详细信息。当你做

var request = {foo: [5, 2, 11] }

axios.get('http://example.com/', request);

axios.get(' http://example.com/', request);

For django application you can receive these as

对于 Django 应用程序,您可以将这些作为

self.request.query_params.getlist('foo')

also.

还。

回答by Yordan Georgiev

If one uses the ready URLSearchParamsthe handling of multiple parameter values with the same name works with axios as well ... I guess the support for IE came in 2017 ... Works on Safari too, although the links claims that it might not ..

如果使用现成的URLSearchParams,则处理具有相同名称的多个参数值也适用于 axios ......我猜对 IE 的支持是在 2017 年出现的......也适用于 Safari,尽管链接声称它可能不会。 .

function getUrlParams(){
        // handles multiple param values with the same name
        var url_params = new URLSearchParams(); 

        if( window.location.toString().indexOf("?") != -1) {
           window.location.search.split('?')[1].split('#')[0]
              .replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
              var attr = decodeURIComponent(key)
              var val = decodeURIComponent(value)
              url_params.append(attr,val);
           });
        } else {
           // create a default set of params - you might not need this one ...
           url_params = { some_param:"some_value" };
        }
        return url_params ;
     }


     function getBackEndData(url_params, back_end_url){
           // the replace is just a fancy way of converting front-end to back-end call
           return axios.get( back_end_url , { params: url_params } )
           .then(response => {
              return response.data ;
           })
           .catch(function(error) {
              return error.response ; 
              console.log(error.response.data);
           })
     }

回答by Alex Pánek

Disclaimer: I have never used Axios and couldn't find any reference in the documentation. It is still worth a try. Personally, I would implement it this way in a library.

免责声明:我从未使用过 Axios,并且在文档中找不到任何参考。还是值得一试的。就个人而言,我会在图书馆中以这种方式实现它。

It might also be possible to pass arrays as values for the parameter:

也可以将数组作为参数值传递:

axios.get('http://example.com/', { foo: [1, 2, 3, 4, 5] });

axios.get('http://example.com/', { foo: [1, 2, 3, 4, 5] });