2026-02-10 09:48:44 +00:00
|
|
|
|
import axios from "axios";
|
|
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
|
if (body && body.code !== "0") {
|
2026-02-26 05:53:58 +00:00
|
|
|
|
const err = new Error(body.msg || "请求失败");
|
|
|
|
|
|
(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-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
|
|
|
|
// Clear session/local storage
|
|
|
|
|
|
localStorage.removeItem("accessToken");
|
|
|
|
|
|
localStorage.removeItem("refreshToken");
|
|
|
|
|
|
sessionStorage.removeItem("userProfile");
|
2026-02-25 05:43:00 +00:00
|
|
|
|
// Force redirect to login with timeout flag
|
|
|
|
|
|
window.location.href = "/login?timeout=1";
|
2026-02-12 07:51:03 +00:00
|
|
|
|
}
|
2026-02-26 05:53:58 +00:00
|
|
|
|
|
|
|
|
|
|
// Process backend error message if available in response body even for non-200 status
|
|
|
|
|
|
const body = error.response?.data;
|
|
|
|
|
|
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;
|