All files / utils request.js
91.66%
Statements
22/24
83.33%
Branches
20/24
80%
Functions
4/5
91.66%
Lines
22/24
Press n or j to go to the next uncovered block, b, p or k for the previous block.
Filter:
| 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 53 54 55 56 57 58 59 60 61 | 1x 1x 1x 1x 7x 7x 7x 6x 7x 1x 1x 1x 7x 6x 6x 6x 5x 5x 5x 4x 4x 7x | import axios from "axios";
import { getToken, clearAuthSession } from "@/utils/storage.js";
import router from "@/router";
import { API_BASE_URL } from "@/utils/fileUrl.js";
const REQUEST_TOKEN_KEY = "__darkRoomRequestToken";
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();
config[REQUEST_TOKEN_KEY] = token;
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("请先登录")
) {
const failedToken = error.config?.[REQUEST_TOKEN_KEY];
const ownsCurrentSession =
Object.prototype.hasOwnProperty.call(error.config ?? {}, REQUEST_TOKEN_KEY) &&
failedToken === getToken();
if (ownsCurrentSession) {
clearAuthSession();
router.push("/login");
}
}
}
return Promise.reject(error);
}
);
export default request;
|