當參數是JSON對象
時,默認的Content-Type是application/json。
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
此時傳遞的參數是Request Payload格式{firstName:"Fred",lastName:"Flintstone"}
如果出現
No 'Access-Control-Allow-Origin' header is present on the requested resource
的錯誤,則是跨域問題。本人喜歡直接配置服務器來解決跨域:例如Nginx配置:Nginx配置跨域請求
當參數是JSON字符串
時,默認的Content-Type是application/x-www-form-urlencoded。
axios.post('/user', JSON.stringify({
firstName: 'Fred',
lastName: 'Flintstone'
}))
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
此時傳遞的參數是Form Data格式key : value
:
{"firstName":"Fred","lastName":"Flintstone"}:
如上。其實這是一個無效的數據,key爲{"firstName":"Fred","lastName":"Flintstone"}
,value爲空。
URLSearchParams
和qs
兩種方式。我更喜歡使用qs庫
的方式,代碼如下:
axios.interceptors.request.use((req) => {
if (req.method === 'post') {
req.data = qs.stringify(req.data);
}
return req;
}, (error) => Promise.reject(error));
之後使用axios的時候,只需要傳遞json對象就可以:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});