2026-04-21 10:13:31 +08:00
|
|
|
|
import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
|
|
|
|
|
|
import envConfig from '../../env';
|
|
|
|
|
|
import Cookies from 'js-cookie';
|
2026-04-17 17:20:41 +08:00
|
|
|
|
import { message } from 'antd';
|
|
|
|
|
|
|
2026-04-21 14:57:52 +08:00
|
|
|
|
// 🔥 删掉这两行!!!
|
|
|
|
|
|
// import store from '../store';
|
|
|
|
|
|
// import { logout } from '../store/userSlice';
|
2026-04-21 10:13:31 +08:00
|
|
|
|
|
2026-04-21 10:33:48 +08:00
|
|
|
|
const API_BASE_URL = envConfig.baseURL;
|
2026-04-21 10:13:31 +08:00
|
|
|
|
|
|
|
|
|
|
const api = axios.create({
|
2026-04-21 10:33:48 +08:00
|
|
|
|
baseURL: API_BASE_URL,
|
|
|
|
|
|
timeout: 20000,
|
|
|
|
|
|
headers: {
|
|
|
|
|
|
'Content-Type': 'application/json',
|
|
|
|
|
|
},
|
|
|
|
|
|
withCredentials: true,
|
2026-04-17 17:20:41 +08:00
|
|
|
|
});
|
|
|
|
|
|
|
2026-04-21 10:13:31 +08:00
|
|
|
|
// 请求拦截器:自动添加token
|
|
|
|
|
|
api.interceptors.request.use(
|
2026-04-21 10:33:48 +08:00
|
|
|
|
(config: InternalAxiosRequestConfig) => {
|
|
|
|
|
|
const token = localStorage.getItem('token');
|
|
|
|
|
|
if (token && config.headers) {
|
|
|
|
|
|
config.headers['Authorization'] = `Bearer ${token}`;
|
|
|
|
|
|
}
|
|
|
|
|
|
return config;
|
|
|
|
|
|
},
|
|
|
|
|
|
(error: AxiosError) => {
|
|
|
|
|
|
return Promise.reject(error);
|
|
|
|
|
|
}
|
2026-04-17 17:20:41 +08:00
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
|
|
// 响应拦截器
|
2026-04-21 10:13:31 +08:00
|
|
|
|
api.interceptors.response.use(
|
2026-04-22 09:43:55 +08:00
|
|
|
|
(response) => {
|
2026-04-21 14:57:52 +08:00
|
|
|
|
return response.data;
|
2026-04-21 10:33:48 +08:00
|
|
|
|
},
|
2026-04-21 14:57:52 +08:00
|
|
|
|
async (error: AxiosError) => { // 👈 加 async
|
|
|
|
|
|
if (error.response?.status === 401) {
|
2026-04-22 09:43:55 +08:00
|
|
|
|
localStorage.clear();
|
|
|
|
|
|
Cookies.remove('userId');
|
|
|
|
|
|
Cookies.remove('Admin-Token');
|
2026-04-21 14:57:52 +08:00
|
|
|
|
|
|
|
|
|
|
const store = await import('../store');
|
|
|
|
|
|
const { logout } = await import('../store/userSlice');
|
|
|
|
|
|
|
|
|
|
|
|
store.default.dispatch(logout());
|
|
|
|
|
|
window.location.href = '/login';
|
|
|
|
|
|
message.error('会话已过期,请重新登录');
|
2026-04-21 10:33:48 +08:00
|
|
|
|
}
|
2026-04-21 14:57:52 +08:00
|
|
|
|
|
2026-04-21 10:33:48 +08:00
|
|
|
|
return Promise.reject(error);
|
|
|
|
|
|
}
|
2026-04-17 17:20:41 +08:00
|
|
|
|
);
|
|
|
|
|
|
|
2026-04-21 10:13:31 +08:00
|
|
|
|
export default api;
|