最近碰见的问题是当我进行接口请求时,前端代码headers请求头参数传给了后端,并且在浏览器的headers请求头那一块也能看见自定义的headers参数,但是后端抓接口的headers日志并没有参数传递过来,于是我使用了好几种方法
第一种
在拦截器做处理,当我点击时通过拦截器带上headers
import axios from 'axios'
Vue.prototype.$http = axios;
// 添加axios 拦截器 每一个会话 会变动的 SessionId
axios.interceptors.request.use(config => {
console.log(`-----------请求拦截器----------->>`)
console.log(config)
这个是令牌 // var tokenStr="eyJhbGciOiJSUzI1NiIsImtpZCI6IjYyRjI4QTU3MkE5MEQ4NThDRTNBRTlFQjBEOEQzQjk1IiwidHlwIjoiYXQrand0In0.eyJuYmYiOjE2OTAyNDc2MDUsImV4cCI6MTcyMTc4MzYwNSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MDg4IiwiYs48sLwSdJ4P_vWslYe70qUvWnkMRaI6GjbhewGPuzdC0w83xd4A"
// config.headers.Authorization = 'Bearer ' + tokenStr
// config.headers["wxCode"]='081WCjFa102RIF0kdzHa1QHxyD2WCjF5'
// config.headers["Model"]='3'
// config.headers["channelCode"]= 'dis'
//最后必须要加上这个
return config
})
失败 让后端抓接口headers参数还是空
第二种
通过封装的方法 在axios里面放headers参数
import axios from 'axios';
import Vue from 'vue';
import { Notify } from 'vant';
Vue.use(Notify);
import { Toast } from 'vant';
Vue.use(Toast);
import { ipConfig } from '../../public/config'; // 使用解构赋值获取具名导出
Vue.prototype.$ipConfig = ipConfig;
let baseURL = '';
if (process.env.NODE_ENV == "development") {
console.log("开发链接:" + location.origin)
baseURL = '/apiq'
} else {
console.log("生产链接:" + location.origin)
baseURL = Vue.prototype.$ipConfig.target_url
}
export function sendAxios(config) {
// Loading.show('正在加载...');
if (!config.notShowLoading) {
Toast.loading({
duration: 0, // 持续展示 toast
forbidClick: true,
loadingType: 'spinner',
message: '',
})
}
ax()
function ax() {
axios({
// headers: {
// "wxCode":'051ae3Ha1admHF0N5uHa1xBX6c4ae3HM',
// "Model": '3',
// "channelCode": 'dis',
// },
method: config.method || 'post',
baseURL,
url: config.url,
data: {
request: config.data
},
timeout: 30000
})
.then(function (res) {
// 处理成功的响应
if (config.succ && typeof (config.succ) == 'function') {
if (res && res.data) {
let resData = res.data.response || {};
if (res.data.resStatus == "1") {
config.succ(resData);
Toast.clear();
} else {
let errMsg = res.data.msg;
if (errMsg) {
errMsg = `${config.url} \r\n ${errMsg}`;
// 处理错误提示或通知
Toast.clear();
Notify({ type: 'danger', message: errMsg });
}
if (config.fail && typeof (config.fail) == 'function') {
config.fail();
}
}
}
}
})
.catch(function (error) {
// 处理错误信息
Toast.clear();
if (config.fail && typeof (config.fail) == 'function') {
console.log('err-----------------' + error);
// 处理错误提示或通知
// config.fail();
}
});
}
}
失败 后端还是抓不到headers参数
第三种和第二种一样
直接使用axios进行请求
失败
后端还是没有接受到headers参数
最后
查出来这是由于默认情况下,代理请求不会转发自定义头部,要解决这个问题,但是可以通过配置代理服务器来传递自定义头部 通过配置headers ,我们可以在发送代理请求时设置请求头部,这样配置后,发送到代理服务器的请求将包含自定义头部,后台服务器就能够获取到自定义头部了,因为走了代理服务器导致代理请求不会转发自定义头部,通过这个问题让我认识到在工作中得多和后端进行链条使问题能够及时解决
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://your-backend-api.com', changeOrigin: true,
headers: { 'Custom-Header': 'Your Custom Header Value' }
}
}
}
}