全局设置axios拦截器,请求增加username和token

发布时间 2023-08-09 22:36:01作者: lytcreate

在main.js的 new vue之前加入:

axios.interceptors.request.use(
config => {
// 在发送请求前,获取新的 token
var username = window.localStorage.getItem('username');
var authorization = window.localStorage.getItem('token');
console.log(username)
console.log(authorization)
if (username && authorization) {
// 如果这两个字段存在,则添加到请求头
config.headers.authorization = authorization;
config.headers.username = username;
}

return config;
},
error => {
return Promise.reject(error);
}
);