2017-08-23 36 views
0

我在我的Vue項目中使用axios,並且其中一個對我的api的調用涉及POST。我的帖子和獲取都要求使用我的令牌設置Authorization標頭。所有get請求做工精細,但將完全一樣的頭在axios.post導致403axios.post不發送auth頭(但.get)

這裏是我的愛可信代碼:

axios.post('https://my.example.org/myapi/meta?uname=' + uname + '&umetaid=' + post.umeta_id + '&umetavalue=' + post.meta_value, { 
      withCredentials: true, 
      headers: { 'Authorization': 'Bearer ' + mytoken } 
     }) 
    .then(function (response) { 
     console.log(response) 
    }) 
    .catch(function (error) { 
     console.log(error) 
    }) 

這總是導致403錯誤,並檢查了我的請求頭顯示授權標頭永遠不會被髮送。如果我將axios.post更改爲axios.get以上(並且將GET方法添加到我的api代碼中,除了現有的POST,OPTIONS)之外,它將執行得很好。我想我可以這樣離開它,但我認爲當真的執行POST時,使用GET呼叫是不好的做法。有什麼我缺少關於與axios形成POST請求嗎?

+0

什麼消息都在控制檯做一個帖子的時候得到些什麼? –

回答

1

Axios Post請求假定第二個參數是數據,第三個參數是config。

Axios Get request假定第二個參數是config,而數據被附加到URL中。

您正在發送的數據應該作爲第二個參數的URL(對於POST請求)。

代碼應該是:

var data = { 
    'uname': uname, 
    'umetaid': post.umeta_id, 
    'umetavalue': post.meta_value 
} 
var headers = { 
    withCredentials: true, 
    headers: { 'Authorization': 'Bearer ' + mytoken } 
} 
axios.post('https://my.example.org/myapi/meta',data,headers) 
.then(function (response) { 
    console.log(response) 
}) 
.catch(function (error) { 
    console.log(error) 
}) 
+0

謝謝,不敢相信我錯過了! – Stephen