【问题标题】:Multiple fields with same key in query params (axios request)?查询参数(axios 请求)中具有相同键的多个字段?
【发布时间】:2017-08-11 09:37:34
【问题描述】:

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

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

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

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

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

如何发送具有相同键的多个字段的请求?

【问题讨论】:

    标签: javascript parameters request axios


    【解决方案1】:

    免责声明:我从未使用过 Axios 并且在 文档。它仍然值得一试。就个人而言,我会 在库中以这种方式实现它。

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

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

    【讨论】:

    • 抱歉 :( 我在构建 URL 的过程中看到有一个 paramSerializer,您也许可以点击那里并使其也适用于数组?
    • 是的,我目前正在使用query-string 包的stringify() 函数,但我希望能找到不同的方法。虽然可能不存在
    • 你可以向 axios 发送 PR 来解决这个问题 :)
    【解决方案2】:

    来自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
    },
    

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

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

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

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

    要获得没有[] 的请求,您可以使用 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);
    

    这将导致请求为

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

    【讨论】:

      【解决方案3】:

      在 Axios 请求配置中,你可以重写 params 序列化,然后使用 QS NPM 模块 以 repeat 模式序列化数组

      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
      

      【讨论】:

      • 坏消息是,这种方法会导致冒号被转义(不适合 UTC 时间字符串)
      • 我使用了 query-string 模块,它的工作方式类似,但没有 repeat 选项,而是默认执行相同的行为。
      【解决方案4】:

      如果使用现成的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);
                 })
           }
      

      【讨论】:

        【解决方案5】:

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

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

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

        对于 django 应用程序,您可以收到这些

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

        还有。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-09-19
          • 2017-11-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-31
          • 2012-06-18
          • 1970-01-01
          相关资源
          最近更新 更多