import axios from "axios";
|
import router from "../router";
|
import { useAuthStore } from "../stores/auth";
|
|
const http = axios.create({
|
baseURL: "/api",
|
timeout: 15000,
|
});
|
|
function redirectToLoginIfNeeded() {
|
const auth = useAuthStore();
|
auth.clear();
|
if (router.currentRoute.value.path === "/login") {
|
return;
|
}
|
router.push("/login");
|
}
|
|
function redirectToForbiddenIfNeeded() {
|
if (router.currentRoute.value.path === "/403") {
|
return;
|
}
|
router.push("/403");
|
}
|
|
http.interceptors.request.use((config) => {
|
const auth = useAuthStore();
|
if (auth.token) {
|
config.headers.Authorization = auth.token;
|
}
|
return config;
|
});
|
|
http.interceptors.response.use(
|
(res) => {
|
const body = res.data;
|
if (body && body.code === 401) {
|
redirectToLoginIfNeeded();
|
return Promise.reject(new Error(body.message || "未登录或已过期"));
|
}
|
if (body && body.code === 403) {
|
redirectToForbiddenIfNeeded();
|
return Promise.reject(new Error(body.message || "无权限访问"));
|
}
|
if (body && body.success === false) {
|
return Promise.reject(new Error(body.message || "请求失败"));
|
}
|
return res;
|
},
|
(err) => {
|
const status = err.response?.status;
|
const code = err.response?.data?.code;
|
if (status === 401 || code === 401) {
|
redirectToLoginIfNeeded();
|
}
|
if (status === 403 || code === 403) {
|
redirectToForbiddenIfNeeded();
|
}
|
return Promise.reject(err);
|
}
|
);
|
|
export default http;
|