2026-02-10 09:48:44 +00:00
|
|
|
|
import axios from "axios";
|
2026-02-26 09:09:14 +00:00
|
|
|
|
import { message } from "antd";
|
2026-02-10 09:48:44 +00:00
|
|
|
|
|
|
|
|
|
|
const http = axios.create({
|
|
|
|
|
|
baseURL: "",
|
|
|
|
|
|
timeout: 15000
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
http.interceptors.request.use((config) => {
|
|
|
|
|
|
const token = localStorage.getItem("accessToken");
|
|
|
|
|
|
if (token) {
|
|
|
|
|
|
config.headers = config.headers || {};
|
|
|
|
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
|
|
|
|
}
|
|
|
|
|
|
return config;
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
http.interceptors.response.use(
|
|
|
|
|
|
(resp) => {
|
|
|
|
|
|
const body = resp.data;
|
2026-02-26 09:09:14 +00:00
|
|
|
|
// 如果返回的 code 不是 0,表示业务错误
|
2026-02-10 09:48:44 +00:00
|
|
|
|
if (body && body.code !== "0") {
|
2026-02-26 09:09:14 +00:00
|
|
|
|
const errorMsg = body.msg || "请求失败";
|
|
|
|
|
|
message.error(errorMsg); // 自动展示后端错误消息
|
|
|
|
|
|
const err = new Error(errorMsg);
|
2026-02-26 05:53:58 +00:00
|
|
|
|
(err as any).code = body.code;
|
|
|
|
|
|
(err as any).msg = body.msg;
|
|
|
|
|
|
return Promise.reject(err);
|
2026-02-10 09:48:44 +00:00
|
|
|
|
}
|
|
|
|
|
|
return resp;
|
|
|
|
|
|
},
|
2026-02-12 07:51:03 +00:00
|
|
|
|
(error) => {
|
2026-02-26 09:09:14 +00:00
|
|
|
|
// 处理 HTTP 状态码错误 (4xx, 5xx)
|
2026-02-25 05:43:00 +00:00
|
|
|
|
if (error.response && (error.response.status === 401 || error.response.status === 403)) {
|
2026-02-12 07:51:03 +00:00
|
|
|
|
localStorage.removeItem("accessToken");
|
|
|
|
|
|
localStorage.removeItem("refreshToken");
|
|
|
|
|
|
sessionStorage.removeItem("userProfile");
|
2026-02-25 05:43:00 +00:00
|
|
|
|
window.location.href = "/login?timeout=1";
|
2026-02-26 09:09:14 +00:00
|
|
|
|
return Promise.reject(error);
|
2026-02-12 07:51:03 +00:00
|
|
|
|
}
|
2026-02-26 05:53:58 +00:00
|
|
|
|
|
|
|
|
|
|
const body = error.response?.data;
|
2026-02-26 09:09:14 +00:00
|
|
|
|
const errorMsg = body?.msg || error.message || "网络异常";
|
|
|
|
|
|
|
|
|
|
|
|
// 防止重复弹出相同的提示(可选逻辑,根据需要调整)
|
|
|
|
|
|
message.error(errorMsg);
|
|
|
|
|
|
|
2026-02-26 05:53:58 +00:00
|
|
|
|
if (body && body.msg) {
|
|
|
|
|
|
const err = new Error(body.msg);
|
|
|
|
|
|
(err as any).code = body.code;
|
|
|
|
|
|
(err as any).msg = body.msg;
|
|
|
|
|
|
return Promise.reject(err);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-12 07:51:03 +00:00
|
|
|
|
return Promise.reject(error);
|
|
|
|
|
|
}
|
2026-02-10 09:48:44 +00:00
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
|
|
export default http;
|