Files
blog/src/util/request.ts
2025-08-11 17:06:29 +08:00

68 lines
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import router from "@/router";
import type { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from "axios";
import axios from "axios";
import { useCookies } from "vue3-cookies";
const { cookies } = useCookies();
// const baseURL: string = "http://127.0.0.1:7777" + "/api";
const baseURL: string = "https://www.hxyouzi.com" + "/api";
const headers: Record<string, string> = {
"Content-Type": "application/x-www-form-urlencoded",
};
const request = axios.create({
baseURL,
headers,
});
// 添加请求拦截器
request.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
const token = cookies.get("token");
if (token && typeof token === "string" && token.trim() !== "") {
config.headers["Authorization"] = "Bearer " + token;
} else delete config.headers["Authorization"];
return config;
},
function (error: AxiosError): string {
// 对请求错误做些什么
return error.message || "Request error";
}
);
// 添加响应拦截器
request.interceptors.response.use(
function (response: AxiosResponse): any {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
return response.data;
},
async function (error: AxiosError): Promise<string> {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
console.log("Response error", error);
if (error.response?.status === 401) {
// window.$msg.warning("无效的token");
cookies.remove("token");
cookies.remove("userinfo");
window.$modal({
title: "无效的token",
content: "token已失效需要登录请登录 =>",
handdleSubmit: () => {
router.replace("/login");
},
});
// router.replace("/login");
return "Unauthorized";
}
return error.message || "Response error";
}
);
export default request;