Files
web-Iot/src/api/request.ts

96 lines
2.1 KiB
TypeScript
Raw Normal View History

2026-04-21 10:13:31 +08:00
import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import envConfig from '../../env';
import Cookies from 'js-cookie';
import utils from '../lib/utils';
2026-04-17 17:20:41 +08:00
2026-04-21 10:33:48 +08:00
const API_BASE_URL = envConfig.baseURL;
const message = utils.message; // 使用全局 message
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: 100000,
2026-04-21 10:33:48 +08:00
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
2026-04-17 17:20:41 +08:00
});
2026-04-30 10:49:44 +08:00
// 请求拦截器
2026-04-21 10:13:31 +08:00
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
);
// 🔥 全局唯一锁:保证并发多个 401 也只执行一次
let isLoggingOut = false;
2026-05-11 16:34:44 +08:00
const handleLogoutAndRedirect = () => {
// 已经在登出流程中,直接阻止
if (isLoggingOut) return;
// 立即上锁
isLoggingOut = true;
2026-05-11 16:34:44 +08:00
// 清除登录信息
try {
localStorage.clear();
Cookies.remove('userId');
Cookies.remove('Admin-Token');
Cookies.remove('token');
} catch { }
// redux 登出
import('../store').then(storeModule => {
2026-05-11 16:34:44 +08:00
import('../store/userSlice').then(({ logout }) => {
storeModule.default.dispatch(logout());
2026-05-11 16:34:44 +08:00
});
});
// 只提示一次
message?.error('登录已过期,请重新登录');
// 只跳转一次
2026-05-11 16:34:44 +08:00
setTimeout(() => {
window.location.href = '/login';
}, 800);
};
// 响应拦截器
2026-04-21 10:13:31 +08:00
api.interceptors.response.use(
2026-05-11 16:34:44 +08:00
(response: AxiosResponse) => {
const data = response.data;
// 业务 401 → 统一走登出
if (data?.code === 401) {
2026-05-11 16:34:44 +08:00
handleLogoutAndRedirect();
return Promise.reject(new Error('登录已过期'));
}
return data;
},
(error: AxiosError) => {
// HTTP 401 → 统一走登出
if (error.response?.status == 401) {
2026-05-11 16:34:44 +08:00
handleLogoutAndRedirect();
2026-04-30 10:49:44 +08:00
return Promise.reject(error);
}
2026-04-21 14:57:52 +08:00
// 网络异常
if (!error.response) {
message?.error('网络异常,请稍后重试');
2026-05-11 16:34:44 +08:00
return Promise.reject(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;