首页+登录页
This commit is contained in:
58
src/util/request.ts
Normal file
58
src/util/request.ts
Normal file
@ -0,0 +1,58 @@
|
||||
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");
|
||||
// router.replace("/login");
|
||||
// return "Unauthorized";
|
||||
// }
|
||||
|
||||
return error.message || "Response error";
|
||||
}
|
||||
);
|
||||
|
||||
export default request;
|
Reference in New Issue
Block a user