【问题标题】:Why 'axios' and $http (vue-resource) behave differently for json query string?为什么 'axios' 和 $http (vue-resource) 对于 json 查询字符串的行为不同?
【发布时间】:2018-02-24 12:42:12
【问题描述】:

我正在开发一个vue 应用程序并从我使用vue-resource 的服务器获取数据

我使用 vue-resource 的代码是

this.$http.get('api/url', {
     params: {
         authData: authData,
         otherData: otherData
     }
})

这里的authdata是json字符串,类似于{"userName":"User+name","id":"userid",....}

现在由于某些原因我不得不搬到axios 所以我将我的代码更改为

axios.get('api/url', {
     params: {
         authData: authData,
         otherData: otherData
     }
})

在这两种情况下,数据都是相同的,但是当我看到网络调用时。我得到了不同的结果。

第一种情况网络调用中的查询字符串是

authData[userName]: 'User+name'
authData[id]    : 'userid'
otherData: 'otherData'

第二种情况网络调用中的查询字符串是

authData: {"userName":"User+name","id":"userid"....}
otherData: 'otherData'

现在我的问题是为什么会发生这种情况以及如何在axios 中实现第一种格式。我不想手动将 json 字符串转换为数组

【问题讨论】:

    标签: json vue.js axios vue-resource


    【解决方案1】:

    这是因为 Axios 将 JavaScript 对象序列化为 JSON。要以 application/x-www-form-urlencoded 格式序列化,您需要使用techniques described in the Axios documentation 之一。

    我认为qs 对你来说是一个不错的解决方案:

    // Use object shorthand notation if it's supported in your environment
    axios.post('/foo', qs.stringify({ authData, otherData }));
    

    【讨论】:

      【解决方案2】:

      Axios 在发送参数时默认为 application/json,而 vue-resource 在您的情况下以 application/x-www-form-urlencoded 格式发送参数。

      您可以使用我从 gist 获得的这个函数,并使用它将您的对象转换为 URL 编码的字符串。

      function JSON_to_URLEncoded(element, key, list){
        var list = list || [];
        if (typeof(element) == 'object'){
          for (var idx in element)
            JSON_to_URLEncoded(element[idx],key?key+'['+idx+']':idx,list);
        } else {
          list.push(key+'='+encodeURIComponent(element));
        }
        return list.join('&');
      }
      

      你可以这样使用它:

      var params = JSON_to_URLEncoded({auth: {username: 'someUser', id: 'someID'}, other: 'other'})
      console.log(params)
      
      axios.get('/url?' + params, {
        headers: {
          contentType: 'x-www-form-urlencoded'
        }
      })
      

      【讨论】:

        猜你喜欢
        • 2013-10-30
        • 1970-01-01
        • 2022-01-19
        • 1970-01-01
        • 2015-12-29
        • 1970-01-01
        • 2018-12-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多