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({ |
yyyang | 3bd72f0 | 2025-06-03 16:35:11 +0800 | [diff] [blame^] | 6 | baseURL: "/api", |
ybt | da5978b | 2025-05-31 15:58:05 +0800 | [diff] [blame] | 7 | timeout: 10000, |
| 8 | }); |
| 9 | |
| 10 | // 请求拦截器 |
| 11 | // 请求拦截器中添加角色检查 |
| 12 | request.interceptors.request.use( |
| 13 | (config) => { |
| 14 | // 从 localStorage 获取 token |
| 15 | const token = localStorage.getItem("token"); |
| 16 | |
| 17 | // 如果有 token 则添加到请求头 |
| 18 | if (token) { |
| 19 | config.headers["Authorization"] = `Bearer ${token}`; |
| 20 | } |
| 21 | |
| 22 | // 角色检查 |
| 23 | // 例如,对特定API路径进行角色检查 |
| 24 | if (config.url.startsWith("/api/admin") && !hasAdminRole()) { |
| 25 | // 取消请求 |
| 26 | return Promise.reject(new Error("无权限执行此操作")); |
| 27 | } |
| 28 | |
| 29 | return config; |
| 30 | }, |
| 31 | (error) => { |
| 32 | return Promise.reject(error); |
| 33 | } |
| 34 | ); |
| 35 | |
| 36 | // 辅助函数:检查是否有管理员角色 |
| 37 | function hasAdminRole() { |
| 38 | const user = JSON.parse(localStorage.getItem("user") || "{}"); |
| 39 | return user.role === "admin"; |
| 40 | } |
| 41 | |
| 42 | // 响应拦截器 |
| 43 | request.interceptors.response.use( |
| 44 | (response) => { |
| 45 | return response; |
| 46 | }, |
| 47 | (error) => { |
| 48 | if (error.response) { |
| 49 | const { status, data } = error.response; |
| 50 | |
| 51 | // 处理 401 未授权错误(token 无效或过期) |
| 52 | if (status === 401) { |
| 53 | message.error("登录已过期,请重新登录"); |
| 54 | |
| 55 | // 清除本地存储的 token 和用户信息 |
| 56 | localStorage.removeItem("token"); |
| 57 | localStorage.removeItem("user"); |
| 58 | |
| 59 | // 重定向到登录页 |
| 60 | if (window.location.pathname !== "/login") { |
| 61 | window.location.href = "/login"; |
| 62 | } |
| 63 | } else { |
| 64 | // 处理其他错误 |
| 65 | message.error(data.message || "请求失败"); |
| 66 | } |
| 67 | } else if (error.request) { |
| 68 | // 请求发出但没有收到响应 |
| 69 | message.error("网络错误,请检查您的网络连接"); |
| 70 | } else { |
| 71 | // 请求配置出错 |
| 72 | message.error("请求配置错误"); |
| 73 | } |
| 74 | |
| 75 | return Promise.reject(error); |
| 76 | } |
| 77 | ); |
| 78 | |
| 79 | export default request; |