longz
2026-04-28 bfa7d3b23e526809b04299d9c2719c3449aba3be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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");
}
 
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.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();
    }
    return Promise.reject(err);
  }
);
 
export default http;