最近在工作中碰到一個問題,后端提供的get請求的接口需要在request header 設置Content-Type為 ‘application/json’,于是如下設置:
const http = axios.create({
method,
baseUrl,
url,
headers: {
'Content-Type': 'application/json',
},
...
})
然而實際使用中發現并沒有成功在請求頭里設置Content-Type,經過網上的資料查找發現是由于axios的源碼出了問題,具體位置在 axios/lib/adapters/xhr.js:
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
從中可以看出當未設置requestData的時候回刪掉Content-Type的設置,其這么做的原因在于是Get請求本身是不需要Content-Type的。
具體解決方法如下:
const http = axios.create({
method,
baseUrl,
url,
headers: {
'Content-Type': 'application/json',
},
...
})
http.interceptors.request.use(config => {
if (config.method === 'get') {
// 給data賦值以繞過if判斷
config.data = true
}
config.headers['Content-Type'] = 'application/json'
return config
}, err => Promise.reject(err))
重新調用接口,ok大功告成
參考資料:
https://github.com/axios/axios/issues/362
https://blog.csdn.net/qq_24729895/article/details/80367460