DCFronted/src/api/axiosConfig.js
2025-10-25 16:39:42 +08:00

74 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import axios from 'axios';
import { logoutUser } from '../utils/jwt'; // logoutUser会处理清除存储和重定向
const API_BASE_URL = 'http://zybdatasupport.online:8000'
// const API_BASE_URL = 'http://110.42.61.148/'
// const API_BASE_URL = 'https://api.zybdatasupport.online';
//const API_BASE_URL = 'http://hk.zybdatasupport.online:8000/';
const axiosInstance = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
timeout: 10000
});
// 并发锁:防止多个 401 同时触发重复 logout
let isHandlingUnauthorized = false;
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';
if (token && !noAuthRequired) {
config.headers.Authorization = `Bearer ${token}`;
}
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') {
if (!isHandlingUnauthorized) {
isHandlingUnauthorized = true;
try {
logoutUser(); // 清除token路由守卫将处理跳转
} finally {
// 在短时间后解除锁,避免长时间无法重新登录
setTimeout(() => { isHandlingUnauthorized = false; }, 1000);
}
}
}
// 不需要额外的console.error错误会自然地在调用处被捕获或显示在网络请求中
return Promise.reject(error);
}
);
}
export default axiosInstance;