开发过程中遇到后端提供接口确认为get请求,但是content-type又需要application/x-www-form-urlencoded,否则会返回415报错,请求头不正确
axios({
method: 'get',
url: '',
params: {
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'token':1111
},
}).then(res => {
})
但是请求头里面Content-Type修改不生效,token却正常加进去了
后知悉axios的get请求是不让设置请求头,这点和ajax不一样,而其中的判断依据就是是否存在data,存在data会默认为post请求,允许设置请求头
所以可以设置拦截器然后绕过判断
在请求方法前增加拦截器
axios.interceptors.request.use(config=>{
if(config.method==='get'){
config.data=true
}
config.headers['Content-Type']='application/x-www-form-urlencoded'
return config
},err=>Promise.reject(err))