axios.ts
2.08 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
import Router from "next/router";
// export const baseUrl = location.protocol + '//localhost';
interface AxiosInstanceType extends AxiosInstance {
get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
head<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
options<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
post<T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig
): Promise<T>;
put<T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig
): Promise<T>;
patch<T = any>(
url: string,
data?: any,
config?: AxiosRequestConfig
): Promise<T>;
}
export const CreateAxiosInstance = (
config?: AxiosRequestConfig
): AxiosInstanceType => {
const instance = axios.create({
timeout: 5000,
withCredentials: true,
...config,
});
instance.interceptors.request.use(
function (config: any) {
// 合并请求头
const user = JSON.parse(localStorage.getItem("user") || "{}");
config.headers = {
userToken: user?._id,
};
config.data = config.body.root
return config;
},
function (error) {
// 处理错误请求
return Promise.reject(error);
}
);
instance.interceptors.response.use(
function (response) {
// todo
const { status, data, message } = response as any;
if (status === 200) {
return data;
} else if (status === 401) {
return Router.push("/login");
} else {
// AntdMessage.error(message);
return Promise.reject(response.data);
}
},
function (error) {
if (error.response) {
if (error.response.status === 401) {
return Router.push("/login");
}
}
// AntdMessage.error(error?.response?.data?.message || "服务端异常");
return Promise.reject(error);
}
);
return instance;
};
const request = CreateAxiosInstance({});
export default request;