ybt | 71fb264 | 2025-06-09 00:29:36 +0800 | [diff] [blame^] | 1 | import axios from 'axios'; |
| 2 | |
| 3 | // 创建axios实例 |
| 4 | const api = axios.create({ |
| 5 | baseURL: '/api', // 使用相对路径,让Vite代理处理 |
| 6 | timeout: 10000, |
| 7 | headers: { |
| 8 | 'Content-Type': 'application/json', |
| 9 | } |
| 10 | }); |
| 11 | |
| 12 | // 请求拦截器 |
| 13 | api.interceptors.request.use( |
| 14 | config => { |
| 15 | // 从localStorage获取token |
| 16 | const token = localStorage.getItem('token'); |
| 17 | if (token) { |
| 18 | config.headers.Authorization = `Bearer ${token}`; |
| 19 | } |
| 20 | return config; |
| 21 | }, |
| 22 | error => { |
| 23 | return Promise.reject(error); |
| 24 | } |
| 25 | ); |
| 26 | |
| 27 | // 响应拦截器 |
| 28 | api.interceptors.response.use( |
| 29 | response => { |
| 30 | return response.data; |
| 31 | }, |
| 32 | error => { |
| 33 | if (error.response) { |
| 34 | // 处理401未授权错误 |
| 35 | if (error.response.status === 401) { |
| 36 | localStorage.removeItem('token'); |
| 37 | window.location.href = '/login'; |
| 38 | } |
| 39 | } |
| 40 | return Promise.reject(error); |
| 41 | } |
| 42 | ); |
| 43 | |
| 44 | export default api; |