Skip to content

Commit 3b0901a

Browse files
committed
add: README.md
1 parent c29e57a commit 3b0901a

File tree

1 file changed

+163
-0
lines changed

1 file changed

+163
-0
lines changed
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
## 解决在 vue 中 axios 请求超时的问题
2+
3+
自从使用 Vue2 之后,就使用官方推荐的 axios 的插件来调用 API,在使用过程中,如果服务器或者网络不稳定掉包了, 你们该如何处理呢? 下面我给你们分享一下我的经历。
4+
5+
### 具体原因
6+
最近公司在做一个项目, 服务端数据接口用的是 java 输出的 API, 有时候在调用的过程中会失败, 在谷歌浏览器里边显示 Provisional headers are shown。
7+
8+
按照搜索引擎给出来的解决方案,解决不了我的问题.
9+
10+
最近在研究 AOP 这个开发编程的概念,axios 开发说明里边提到的栏截器 (axios.Interceptors) 应该是这种机制,降低代码耦合度,提高程序的可重用性,同时提高了开发的效率。
11+
12+
### 带坑的解决方案一
13+
我的经验有限,觉得唯一能做的,就是 axios 请求超时之后做一个重新请求。通过研究 axios 的使用说明,给它设置一个 timeout = 6000
14+
15+
16+
```javascript
17+
axios.defaults.timeout = 6000;
18+
```
19+
然后加一个栏截器.
20+
21+
```
22+
// Add a request interceptor
23+
axios.interceptors.request.use(function (config) {
24+
// Do something before request is sent
25+
return config;
26+
}, function (error) {
27+
// Do something with request error
28+
return Promise.reject(error);
29+
});
30+
31+
// Add a response interceptor
32+
axios.interceptors.response.use(function (response) {
33+
// Do something with response data
34+
return response;
35+
}, function (error) {
36+
// Do something with response error
37+
return Promise.reject(error);
38+
});
39+
```
40+
这个栏截器作用是 如果在请求超时之后,栏截器可以捕抓到信息,然后再进行下一步操作,也就是我想要用 重新请求。
41+
42+
这里是相关的页面数据请求。
43+
44+
45+
46+
```
47+
this.$axios.get(url, {params:{load:'noload'}}).then(function (response) {
48+
//dosomething();
49+
}).catch(error => {
50+
// 超时之后在这里捕抓错误信息.
51+
if (error.response) {
52+
console.log('error.response')
53+
console.log(error.response);
54+
} else if (error.request) {
55+
console.log(error.request)
56+
console.log('error.request')
57+
if(error.request.readyState == 4 && error.request.status == 0){
58+
// 我在这里重新请求
59+
}
60+
} else {
61+
console.log('Error', error.message);
62+
}
63+
console.log(error.config);
64+
});
65+
66+
```
67+
超时之后, 报出 Uncaught (in promise) Error: timeout of xxx ms exceeded 的错误。
68+
69+
在 catch 那里,它返回的是 error.request 错误,所以就在这里做 retry 的功能, 经过测试是可以实现重新请求的功功能, 虽然能够实现 超时重新请求的功能,但很麻烦,需要每一个请 API 的页面里边要设置重新请求。
70+
71+
如果项目有几十个.vue 文件,如果每个页面都要去设置超时重新请求的功能,那我要疯掉的.
72+
73+
而且这个机制还有一个严重的 bug,就是被请求的链接失效或其他原因造成无法正常访问的时候,这个机制失效了,它不会等待我设定的 6 秒,而且一直在刷,一秒种请求几十次,很容易就把服务器搞垮了,请看下图, 一眨眼的功能,它就请求了 146 次。
74+
75+
76+
77+
---
78+
79+
### 带坑的解决方案二
80+
研究了 axios 的源代码,超时后, 会在拦截器那里 axios.interceptors.response 捕抓到错误信息, 且 error.code = "ECONNABORTED",具体链接
81+
82+
https://github.com/axios/axios/blob/26b06391f831ef98606ec0ed406d2be1742e9850/lib/adapters/xhr.js#L95-L101
83+
84+
```
85+
// Handle timeout
86+
request.ontimeout = function handleTimeout() {
87+
reject(createError('timeout of' + config.timeout + 'ms exceeded', config, 'ECONNABORTED',
88+
request));
89+
90+
// Clean up request
91+
request = null;
92+
};
93+
```
94+
95+
96+
所以,我的全局超时重新获取的解决方案这样的。
97+
98+
99+
```javascript
100+
axios.interceptors.response.use(function(response) {
101+
// ...
102+
}, function(error){
103+
const originalRequest = error.config;
104+
if(error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1 && !originalRequest._retry){
105+
originalRequest._retry = true
106+
return axios.request(originalRequest);
107+
}
108+
});
109+
```
110+
111+
112+
这个方法,也可以实现得新请求,但有两个问题,1 是它只重新请求 1 次,如果再超时的话,它就停止了,不会再请求。第 2 个问题是,我在每个有数据请求的页面那里,做了许多操作,比如 this.$axios.get(url).then 之后操作。
113+
114+
---
115+
### 完美的解决方法
116+
以 AOP 编程方式,我需要的是一个 超时重新请求的全局功能, 要在 axios.Interceptors 下功夫,在 github 的 axios 的 issue 找了别人的一些解决方法,终于找到了一个完美解决方案,就是下面这个。
117+
118+
https://github.com/axios/axios/issues/164#issuecomment-327837467
119+
120+
121+
122+
```
123+
// 在 main.js 设置全局的请求次数,请求的间隙
124+
axios.defaults.retry = 4;
125+
axios.defaults.retryDelay = 1000;
126+
127+
axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
128+
var config = err.config;
129+
// If config does not exist or the retry option is not set, reject
130+
if(!config || !config.retry) return Promise.reject(err);
131+
132+
// Set the variable for keeping track of the retry count
133+
config.__retryCount = config.__retryCount || 0;
134+
135+
// Check if we've maxed out the total number of retries
136+
if(config.__retryCount>= config.retry) {
137+
// Reject with the error
138+
return Promise.reject(err);
139+
}
140+
141+
// Increase the retry count
142+
config.__retryCount += 1;
143+
144+
// Create new promise to handle exponential backoff
145+
var backoff = new Promise(function(resolve) {
146+
setTimeout(function() {
147+
resolve();
148+
}, config.retryDelay || 1);
149+
});
150+
151+
// Return the promise in which recalls axios to retry the request
152+
return backoff.then(function() {
153+
return axios(config);
154+
});
155+
});
156+
```
157+
其他的那个几十个.vue 页面的 this.$axios 的 get 和 post 的方法根本就不需要去修改它们的代码。
158+
159+
160+
161+
参考文章:https://juejin.im/post/5abe0f94518825558a06bcd9
162+
163+
关注前端开发 关注用户体验 请访问我的新博客: https://www.cssge.com

0 commit comments

Comments
 (0)