在前端使用vue+axios的post發送請求時,在響應的回調函數中獲取不到響應的數據,代碼如下所示
var vm = new Vue({
el: '#app',
data: {
obj: ''
},
methods: {
postData: function() {
var url = 'http://xxxxxxxxxx'
axios.post(url, {
id: '0',
name: 'idNmae'
}).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log(error);
})
}
}
});
打開chrom中的NetWork選項看到請求頭信息中出現一個警告 Provisional headers are shown
,
這時候以爲後端的給的接口除了問題,爲了驗證一下,改使用了vue-resource中的post方法請求了這個接口,發現能夠獲取響應的數據,這時候問題肯定不是接口問題了,問題還是在axios的post請求上,根據 Provisional headers are shown
這個警告分析一下應該是請求頭出現的問題,回想在之前用Ajax的post的請求的時候都要設置請求頭的,那麼就在axios中使用post也設置一下請求頭看可不可以,更改後的代碼如下
var vm = new Vue({
el: '#app',
data: {
obj: ''
},
methods: {
postData: function() {
var url = 'http://xxxxxxxxxx'
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; //此處是增加的代碼,設置請求頭的類型
axios.post(url, {
id: '0',
name: 'idNmae'
}).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log(error);
})
}
}
});
設置了下面之後就能夠請求到響應的信息了。測試OK!
axios.defaults.headers['Content-Type']