刷新多此会跳转到登陆的问题解决了,但是刷新会出现更逆天的问题
This commit is contained in:
@@ -13,48 +13,49 @@ const axiosInstance = axios.create({
|
||||
timeout: 10000
|
||||
});
|
||||
|
||||
/**
|
||||
* 请求拦截器
|
||||
* - 对需要认证的请求,在请求头中添加Authorization
|
||||
* - 对登录、注册和获取列表的请求,不添加Authorization
|
||||
*/
|
||||
axiosInstance.interceptors.request.use(
|
||||
config => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const url = config.url;
|
||||
export function setupInterceptors() {
|
||||
/**
|
||||
* 请求拦截器
|
||||
* - 对需要认证的请求,在请求头中添加Authorization
|
||||
* - 对登录、注册和获取列表的请求,不添加Authorization
|
||||
*/
|
||||
axiosInstance.interceptors.request.use(
|
||||
config => {
|
||||
const token = localStorage.getItem('access_token');
|
||||
const url = config.url;
|
||||
|
||||
// 定义不需要Token的接口条件
|
||||
const noAuthRequired =
|
||||
url === '/user/login' ||
|
||||
url === '/user/register' || // 明确添加注册接口
|
||||
url.endsWith('/getlist');
|
||||
// 定义不需要Token的接口条件
|
||||
const noAuthRequired =
|
||||
url === '/user/login' ||
|
||||
url === '/user/register';
|
||||
|
||||
if (token && !noAuthRequired) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
if (token && !noAuthRequired) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
},
|
||||
error => {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
return config;
|
||||
},
|
||||
error => {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
);
|
||||
|
||||
/**
|
||||
* 响应拦截器
|
||||
* - 如果收到401错误(未授权),并且不是来自登录请求,则调用logoutUser函数清除用户凭证
|
||||
*/
|
||||
axiosInstance.interceptors.response.use(
|
||||
response => response,
|
||||
error => {
|
||||
const originalRequest = error.config;
|
||||
|
||||
// 如果收到401错误,并且不是来自登录请求本身
|
||||
if (error.response && error.response.status === 401 && originalRequest.url !== '/user/login') {
|
||||
logoutUser(); // 调用简化的logoutUser,它只清除token,不导航
|
||||
/**
|
||||
* 响应拦截器
|
||||
* - 如果收到401错误(未授权),并且不是来自登录请求,则调用logoutUser函数清除用户凭证
|
||||
*/
|
||||
axiosInstance.interceptors.response.use(
|
||||
response => response,
|
||||
error => {
|
||||
const originalRequest = error.config;
|
||||
|
||||
// 如果收到401错误,并且不是来自登录请求本身
|
||||
if (error.response && error.response.status === 401 && originalRequest.url !== '/user/login') {
|
||||
logoutUser(); // 调用简化的logoutUser,它只清除token,不导航
|
||||
}
|
||||
// 不需要额外的console.error,错误会自然地在调用处被捕获或显示在网络请求中
|
||||
return Promise.reject(error);
|
||||
}
|
||||
// 不需要额外的console.error,错误会自然地在调用处被捕获或显示在网络请求中
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
);
|
||||
}
|
||||
|
||||
export default axiosInstance;
|
||||
Reference in New Issue
Block a user