背景:
请求后端数据时,接口返回json为空。与后端沟通发现,请求头中缺少
‘X-Requested-With’: ‘XMLHttpRequest’
解决:
1,vue+vant项目中
service.interceptors.request.use(
config => {
config.headers = { ‘X-Requested-With’: ‘XMLHttpRequest’ }
if (store.getters.token) {
config.headers[‘X-Token’] = getToken()
}
return config
},
error => {
return Promise.reject(error)
}
)
在请求中设置请求头:
config.headers = { 'X-Requested-With': 'XMLHttpRequest' }
2.vue+elementui
axios.defaults.headers.common[‘X-Requested-With’] = ‘XMLHttpRequest’
service.interceptors.request.use(
config => {
// do something before request is sent
return config
},
error => {
return Promise.reject(error