All files / utils request.js

89.47% Statements 17/19
83.33% Branches 15/18
80% Functions 4/5
89.47% Lines 17/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 50 51 52            1x             1x           1x   2x 2x 1x   2x   1x     1x 1x   6x 5x 5x 5x           4x 4x     6x          
import axios from "axios";
import { getToken, clearAuthSession } from "@/utils/storage.js";
import router from "@/router";
import { API_BASE_URL } from "@/utils/fileUrl.js";
 
const demoAdapter =
  import.meta.env.VITE_DEMO_MODE === "true"
    ? async (config) => {
        const { demoAdapter: adapter } = await import("@/demo/adapter.js");
        return adapter(config);
      }
    : undefined;
 
const request = axios.create({
  baseURL: API_BASE_URL,
  timeout: 8000,
  ...(demoAdapter ? { adapter: demoAdapter } : {}),
});
 
request.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);
 
request.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response) {
      const { status, data } = error.response;
      const authMessage = data && typeof data.msg === "string" ? data.msg : "";
      if (
        status === 401 ||
        data?.code === 401 ||
        authMessage.includes("身份认证") ||
        authMessage.includes("请先登录")
      ) {
        clearAuthSession();
        router.push("/login");
      }
    }
    return Promise.reject(error);
  }
);
 
export default request;