55 lines
1.2 KiB
JavaScript
55 lines
1.2 KiB
JavaScript
import { message } from "antd";
|
|
import axios from "axios";
|
|
import { logout } from "../features/auth/authSlice";
|
|
|
|
const baseURL = "http://127.0.0.1:8080";
|
|
|
|
const axiosInstance = axios.create({
|
|
baseURL: baseURL,
|
|
timeout: 2000, // 2秒
|
|
});
|
|
|
|
axiosInstance.interceptors.request.use(
|
|
(config) => {
|
|
const token = localStorage.getItem("token");
|
|
if (token) {
|
|
config.headers.Authorization = `Bearer ${token}`;
|
|
}
|
|
return config;
|
|
},
|
|
(error) => Promise.reject(error)
|
|
);
|
|
|
|
axiosInstance.interceptors.response.use(
|
|
(response) => {
|
|
const config = response.config;
|
|
// 如果设置了跳过,直接返回原始 response
|
|
if (config.skipInterceptor) {
|
|
return response;
|
|
}
|
|
const { code, message: msg, data } = response.data;
|
|
|
|
if (code === 0) {
|
|
return data;
|
|
} else {
|
|
message.error(msg);
|
|
return Promise.reject(new Error(msg));
|
|
}
|
|
},
|
|
async (error) => {
|
|
if (error.response) {
|
|
const status = error.response.status;
|
|
|
|
const { store } = await import("../store");
|
|
if (status === 403) {
|
|
message.error("请登录后重试");
|
|
store.dispatch(logout());
|
|
window.location.href = "/login";
|
|
}
|
|
}
|
|
}
|
|
);
|
|
|
|
export { baseURL };
|
|
export default axiosInstance;
|