// 添加请求拦截器
service.interceptors.request.use(
(config) => {
// // 在发送请求之前做些什么 token
// if (Session.get('token')) {
// (<any>config.headers).common['Authorization'] = `${Session.get('token')}`;
// }
// 获取本地的 token
config.withCredentials = true;
const accessToken = Local.get(accessTokenKey);
if (accessToken) {
// 将 token 添加到请求报文头中
config.headers!['Authorization'] = `Bearer ${accessToken}`;
// 判断 accessToken 是否过期
const jwt: any = decryptJWT(accessToken);
const exp = getJWTDate(jwt.exp as number);
// token 已经过期
if (new Date() >= exp) {
// 获取刷新 token
const refreshAccessToken = Local.get(refreshAccessTokenKey);
// 携带刷新 token
if (refreshAccessToken) {
config.headers!['X-Authorization'] = `Bearer ${refreshAccessToken}`;
}
}
// debugger
// get请求映射params参数
if (config.method?.toLowerCase() === 'get' && config.data) {
let url = config.url + '?' + tansParams(config.data);
url = url.slice(0, -1);
config.data = {};
config.url = url;
}
}
return config;
},
(error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
允许跨域cookie
config.withCredentials = true;
标签:axios,const,跨域,accessToken,get,url,token,cookie,config
From: https://www.cnblogs.com/shiningrise/p/18424931