2017-09-15 107 views
2

我開發一個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字符串手動轉換爲數組

回答

3

發生這種情況是因爲Axios將JavaScript對象序列化爲JSON。要以application/x-www-form-urlencoded格式進行序列化,您需要使用techniques described in the Axios documentation之一。發送PARAMS時,而在你的情況VUE資源application/x-www-form-urlencoded格式發送他們

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

Axios公司默認爲application/json

我覺得qs對你是一個很好的解決方案。

您可以使用此函數從此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' 
    } 
}) 
相關問題