Axios 实现请求失败自动重试

源码

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
import {ElMessage} from "element-plus";

// obj 传入一个 axios 实例
export default function setupRequest(obj) {
obj.interceptors.request.use(
config => {
// 请求前的操作
config.headers['X-Requested-With'] = 'XMLHttpRequest'
config.__retryTimes = 2
// 超时时间 5s,若因超时而失败会重试 __retryTimes 次
config.timeout = 5000
return config
},
error => {
return Promise.reject(error)
}
)

obj.interceptors.response.use(
response => {
return response
},
error => {
let config = error.config
if (
(!config || !config.__retryTimes) ||
(error.response && error.response.status < 500) ||
(config.__retryCount >= config.__retryTimes)
) {
if (!error.response) {
ElMessage({
message: '请求失败,请检查网络连接。',
type: 'error',
duration: 5 * 1000
})
}
else if (error.response.status === 419) {
ElMessage({
message: '页面已过期,请刷新重试。',
type: 'error',
duration: 5 * 1000
})
}
return Promise.reject(error);
}

// 设置重试次数
config.__retryCount = 0 | config.__retryCount
// 设置重试时间
config.retryDelay = 500
// 重试次数自增
error.config.__retryCount ++;

// 延时处理
const delay = new Promise((resolve) => {
setTimeout(() => {
resolve();
}, error.config.retryDelay);
});
// 重新发起请求
return delay.then(() => {
return obj(error.config);
});
}
)

}

export var baseUrl = 'http://' + window.location.host

注意

这里的 __retryCount 的初始化即 config.__retryCount = 0 不能出现在 request 拦截器中,会导致每次的 __retryCount 都被重置,从而导致重试进入死循环。