-
Notifications
You must be signed in to change notification settings - Fork 31
/
index.ts
75 lines (69 loc) · 2.12 KB
/
index.ts
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
/*
* @Author: guokai05
* @Date: 2023-02-19 22:31:15
* @LastEditors: guokai05
* @LastEditTime: 2023-02-21 16:18:27
*/
import axios from 'axios';
import axiosRetry from 'axios-retry';
import {InternalAxiosRequestConfig, AxiosRequestConfig, AxiosResponse, AxiosError} from 'axios';
const whiteRetry = new Set(['ECONNABORTED', undefined, 0]);
// import {baseURL} from '@/utils/variable';
// 创建 axios 请求实例
const serviceAxios = axios.create({
baseURL: '', // 接口请求地址
timeout: 15 * 1000, // 请求超时设置
withCredentials: false, // 跨域请求是否需要携带 cookie
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
validateStatus() {
// 使用async-await,处理reject情况较为繁琐,所以全部返回resolve,在业务代码中处理异常
return true;
}
});
axiosRetry(serviceAxios, {
retries: 2, // 重复请求次数
shouldResetTimeout: true, // 重置超时时间
retryDelay: (retryCount) => {
return retryCount * 10000; // 重复请求延迟
},
retryCondition: (err) => {
// true为打开自动发送请求,false为关闭自动发送请求
const {code, message} = err;
return whiteRetry.has(<string>code) || message.includes('timeout');
}
});
// 请求拦截器
serviceAxios.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
return config;
},
(err: AxiosError) => {
return Promise.reject(err);
}
);
// 响应拦截器
serviceAxios.interceptors.response.use(
(res: AxiosResponse) => {
return res;
},
(err: AxiosError) => {
return Promise.reject(err);
}
);
// 统一发起请求的函数
async function request<T>(options: AxiosRequestConfig) {
try {
const response = await serviceAxios.request<T>(options);
const {status, data} = response;
// 处理 HTTP 状态码
if (status < 200 || status >= 500) {
return Promise.reject();
}
return Promise.resolve(data);
} catch (error) {
return Promise.reject(error);
}
}
export default request;