ybt | da5978b | 2025-05-31 15:58:05 +0800 | [diff] [blame] | 1 | import axios from "axios"; |
| 2 | import { message } from "antd"; |
| 3 | |
| 4 | // 创建 axios 实例 |
| 5 | const request = axios.create({ |
ybt | ff3665a | 2025-06-09 23:53:39 +0800 | [diff] [blame^] | 6 | baseURL: "http://192.168.10.174:8080/api", |
ybt | da5978b | 2025-05-31 15:58:05 +0800 | [diff] [blame] | 7 | timeout: 10000, |
| 8 | }); |
| 9 | |
| 10 | // 请求拦截器 |
ybt | da5978b | 2025-05-31 15:58:05 +0800 | [diff] [blame] | 11 | request.interceptors.request.use( |
| 12 | (config) => { |
| 13 | // 从 localStorage 获取 token |
| 14 | const token = localStorage.getItem("token"); |
| 15 | |
| 16 | // 如果有 token 则添加到请求头 |
| 17 | if (token) { |
ybt | bac75f2 | 2025-06-08 22:31:15 +0800 | [diff] [blame] | 18 | config.headers["token"] = token; |
ybt | da5978b | 2025-05-31 15:58:05 +0800 | [diff] [blame] | 19 | } |
| 20 | |
ybt | da5978b | 2025-05-31 15:58:05 +0800 | [diff] [blame] | 21 | |
ybt | bac75f2 | 2025-06-08 22:31:15 +0800 | [diff] [blame] | 22 | console.log("发出的请求", config); |
ybt | da5978b | 2025-05-31 15:58:05 +0800 | [diff] [blame] | 23 | return config; |
| 24 | }, |
| 25 | (error) => { |
| 26 | return Promise.reject(error); |
| 27 | } |
| 28 | ); |
| 29 | |
ybt | da5978b | 2025-05-31 15:58:05 +0800 | [diff] [blame] | 30 | |
| 31 | // 响应拦截器 |
| 32 | request.interceptors.response.use( |
| 33 | (response) => { |
ybt | bac75f2 | 2025-06-08 22:31:15 +0800 | [diff] [blame] | 34 | return response.data; |
ybt | da5978b | 2025-05-31 15:58:05 +0800 | [diff] [blame] | 35 | }, |
| 36 | (error) => { |
| 37 | if (error.response) { |
| 38 | const { status, data } = error.response; |
| 39 | |
| 40 | // 处理 401 未授权错误(token 无效或过期) |
| 41 | if (status === 401) { |
| 42 | message.error("登录已过期,请重新登录"); |
| 43 | |
| 44 | // 清除本地存储的 token 和用户信息 |
| 45 | localStorage.removeItem("token"); |
| 46 | localStorage.removeItem("user"); |
| 47 | |
| 48 | // 重定向到登录页 |
| 49 | if (window.location.pathname !== "/login") { |
| 50 | window.location.href = "/login"; |
| 51 | } |
| 52 | } else { |
| 53 | // 处理其他错误 |
ybt | bac75f2 | 2025-06-08 22:31:15 +0800 | [diff] [blame] | 54 | // message.error(data.message || "11111请求失败"); |
| 55 | message.error(data.message || "11111请求失败"); |
ybt | da5978b | 2025-05-31 15:58:05 +0800 | [diff] [blame] | 56 | } |
| 57 | } else if (error.request) { |
| 58 | // 请求发出但没有收到响应 |
| 59 | message.error("网络错误,请检查您的网络连接"); |
| 60 | } else { |
| 61 | // 请求配置出错 |
ybt | 0d010e5 | 2025-06-09 00:29:36 +0800 | [diff] [blame] | 62 | message.error(error.message || "请求配置错误"); |
ybt | da5978b | 2025-05-31 15:58:05 +0800 | [diff] [blame] | 63 | } |
| 64 | |
| 65 | return Promise.reject(error); |
| 66 | } |
| 67 | ); |
| 68 | |
ybt | bac75f2 | 2025-06-08 22:31:15 +0800 | [diff] [blame] | 69 | export default request; |