import axios from 'axios'; const api = axios.create({ baseURL: '/api', timeout: 30000, withCredentials: true, // 携带 httpOnly cookie }); // 响应拦截:统一错误处理 api.interceptors.response.use( (response) => response.data, (error) => { // 仅在“已登录后 token 失效”时清除登录态并跳转登录页。 // 登录接口本身返回 401(用户名/密码错误)时不应跳转,否则会吞掉错误提示。 if (error.response?.status === 401 && error.config?.url !== '/auth/login') { localStorage.removeItem('user'); window.location.href = '/login'; } const detail = error.response?.data?.detail; let msg = error.message || '请求失败'; if (typeof detail === 'string') { msg = detail; } else if (Array.isArray(detail) && detail.length > 0) { msg = detail.map((d: any) => d?.msg || (typeof d === 'string' ? d : JSON.stringify(d))).join('; '); } else if (detail && typeof detail === 'object') { msg = JSON.stringify(detail); } return Promise.reject(new Error(msg)); } ); export default api;