为什么' axios'和$ http(vue-resource)对json查询字符串的行为有所不同?

时间:2017-09-15 10:37:40

标签: json vue.js axios vue-resource

我正在开发一个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字符串转换为数组

2 个答案:

答案 0 :(得分:3)

这是因为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 }));

答案 1 :(得分:1)

发送参数时,

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'
  }
})