import axios, { type AxiosRequestConfig } from 'axios'; const instance = axios.create({ baseURL: '/api', timeout: 10000, }); instance.interceptors.request.use((config) => { const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }); instance.interceptors.response.use( (res) => res.data, (err) => { if (err.response?.status === 401) { localStorage.removeItem('token'); localStorage.removeItem('user'); localStorage.removeItem('permissions'); window.location.href = '/login'; } if (err.response?.status === 403) { const msg = err.response?.data?.message || '权限不足'; console.warn('[403]', msg); } return Promise.reject(err.response?.data || err); }, ); const request = ( method: string, url: string, data?: unknown, config?: AxiosRequestConfig, ): Promise => instance.request({ ...config, method, url, data }) as Promise; const api = { get: (url: string, config?: AxiosRequestConfig): Promise => request('get', url, undefined, config), post: (url: string, data?: unknown, config?: AxiosRequestConfig): Promise => request('post', url, data, config), put: (url: string, data?: unknown, config?: AxiosRequestConfig): Promise => request('put', url, data, config), patch: (url: string, data?: unknown, config?: AxiosRequestConfig): Promise => request('patch', url, data, config), delete: (url: string, config?: AxiosRequestConfig): Promise => request('delete', url, undefined, config), }; export default api;