interceptor.ts
1.7 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
import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message } from '@arco-design/web-vue';
import { getToken } from '@/utils/auth';
export interface HttpResponse<T = unknown> {
status: 'success' | 'fail' | 'error';
msg: string;
code: number;
data: T;
}
export interface ServiceResponse<T = unknown> extends HttpResponse<T> {
meta: { current: number; limit: number; total: number };
}
if (import.meta.env.VITE_API_URL) {
axios.defaults.baseURL = import.meta.env.VITE_API_URL;
}
axios.interceptors.request.use(
// @ts-ignore
(config: AxiosRequestConfig) => {
if (!config.url?.startsWith('/provider')) {
config.baseURL = `${config.baseURL}/user`;
}
const token = getToken();
if (token) {
if (!config.headers) {
config.headers = {};
}
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
// do something
return Promise.reject(error);
}
);
// add response interceptors
axios.interceptors.response.use(
// @ts-ignore
async (response: AxiosResponse<ServiceResponse>): Promise<ServiceResponse | unknown> => {
if (response.data instanceof Blob) {
return Promise.resolve(response);
}
return Promise.resolve(response.data);
},
(error) => {
if (error.response.status === 401) {
// clearToken();
window.location.reload();
Message.warning({ id: 'token_lose', content: '登陆信息已失效,请重新登陆...' });
} else {
Message.error({
id: 'service_error',
content: error.response.data.msg || error.msg || 'Request Error',
duration: 5 * 1000,
});
}
return Promise.reject(error);
}
);