您现在的位置是:首页 > 技术教程 正文

axios请求超时,设置重新请求的完美解决方法

admin 阅读: 2024-03-31
后台-插件-广告管理-内容页头部广告(手机)

自从使用Vue2之后,就使用官方推荐的axios的插件来调用API,在使用过程中,如果服务器或者网络不稳定掉包了, 你们该如何处理呢? 下面我给你们分享一下我的经历。

具体原因

最近公司在做一个项目, 服务端数据接口用的是Php输出的API, 有时候在调用的过程中会失败, 在谷歌浏览器里边显示Provisional headers are shown。

%20 %20%20%20 %20%20 %20

按照搜索引擎给出来的解决方案,解决不了我的问题.

%20 %20

%20 %20

最近在研究AOP这个开发编程的概念,axios开发说明里边提到的栏截器(axios.Interceptors)应该是这种机制,降低代码耦合度,提高程序的可重用性,同时提高了开发的效率。

%20 %20

%20 %20
带坑的解决方案一
%20 %20

我的经验有限,觉得唯一能做的,就是axios请求超时之后做一个重新请求。通过研究%20axios的使用说明,给它设置一个timeout%20=%206000

%20 %20

%20 %20axios.defaults.timeout%20=%20%206000;%20 %20

然后加一个栏截器.

%20 %20

%20 %20
  1. //%20Add%20a%20request%20interceptor
  2. axios.interceptors.request.use(function%20(config)%20{
  3. %20%20%20%20//%20Do%20something%20before%20request%20is%20sent
  4. %20%20%20%20return%20config;
  5. %20%20},%20function%20(error)%20{
  6. %20%20%20%20//%20Do%20something%20with%20request%20error
  7. %20%20%20%20return%20Promise.reject(error);
  8. });
  9. //%20Add%20a%20response%20interceptor
  10. axios.interceptors.response.use(function%20(response)%20{
  11. %20%20%20%20//%20Do%20something%20with%20response%20data
  12. %20%20%20%20return%20response;
  13. %20%20},%20function%20(error)%20{
  14. %20%20%20%20//%20Do%20something%20with%20response%20error
  15. %20%20%20%20return%20Promise.reject(error);
  16. });

这个栏截器作用是 如果在请求超时之后,栏截器可以捕抓到信息,然后再进行下一步操作,也就是我想要用 重新请求。

这里是相关的页面数据请求。

  1. this.$axios.get(url, {params:{load:'noload'}}).then(function (response) {
  2. //dosomething();
  3. }).catch(error => {
  4. //超时之后在这里捕抓错误信息.
  5. if (error.response) {
  6. console.log('error.response')
  7. console.log(error.response);
  8. } else if (error.request) {
  9. console.log(error.request)
  10. console.log('error.request')
  11. if(error.request.readyState == 4 && error.request.status == 0){
  12. //我在这里重新请求
  13. }
  14. } else {
  15. console.log('Error', error.message);
  16. }
  17. console.log(error.config);
  18. });

超时之后, 报出 Uncaught (in promise) Error: timeout of xxx ms exceeded的错误。

%20 %20%20%20 %20%20 %20

在%20catch那里,它返回的是error.request错误,所以就在这里做%20retry的功能,%20经过测试是可以实现重新请求的功功能,%20虽然能够实现%20超时重新请求的功能,但很麻烦,需要每一个请API的页面里边要设置重新请求。

%20 %20

%20 %20%20 %20%20%20 %20%20%20%20 %20%20%20%20%20 %20%20%20 %20%20 %20

看上面,我这个项目有几十个.vue%20文件,如果每个页面都要去设置超时重新请求的功能,那我要疯掉的.

%20 %20

%20 %20

而且这个机制还有一个严重的bug,就是被请求的链接失效或其他原因造成无法正常访问的时候,这个机制失效了,它不会等待我设定的6秒,而且一直在刷,一秒种请求几十次,很容易就把服务器搞垮了,请看下图,%20一眨眼的功能,它就请求了146次。

%20 %20%20 %20%20%20 %20%20%20%20 %20%20%20%20%20 %20%20%20 %20%20 %20

%20 %20

%20 %20
带坑的解决方案二
%20 %20

研究了axios的源代码,超时后,%20会在拦截器那里%20axios.interceptors.response%20捕抓到错误信息,%20且%20error.code%20=%20“ECONNABORTED”,具体链接

%20 %20

https://github.com/axios/axios/blob/26b06391f831ef98606ec0ed406d2be1742e9850/lib/adapters/xhr.js#L95-L101

%20 %20
  1. //%20Handle%20timeout
  2. request.ontimeout%20=%20function%20handleTimeout()%20{
  3. %20%20reject(createError('timeout%20of%20'%20+%20config.timeout%20+%20'ms%20exceeded',%20config,%20'ECONNABORTED',
  4. %20%20%20%20request));
  5. %20%20//%20Clean%20up%20request
  6. %20%20request%20=%20null;
  7. };
%20 %20

所以,我的全局超时重新获取的解决方案这样的。

%20 %20
  1. axios.interceptors.response.use(function(response){
  2. ....
  3. },%20function(error){
  4. %20%20%20%20var%20originalRequest%20=%20error.config;
  5. %20%20%20%20if(error.code%20==%20'ECONNABORTED'%20&&%20error.message.indexOf('timeout')!=-1%20&&%20!originalRequest._retry){
  6. %20%20%20%20%20%20%20%20%20%20%20%20originalRequest._retry%20=%20true
  7. %20%20%20%20%20%20%20%20%20%20%20%20return%20axios.request(originalRequest);
  8. %20%20%20%20}
  9. });
%20 %20

这个方法,也可以实现得新请求,但有两个问题,1是它只重新请求1次,如果再超时的话,它就停止了,不会再请求。第2个问题是,我在每个有数据请求的页面那里,做了许多操作,比如%20this.$axios.get(url).then之后操作。

%20 %20

%20 %20
完成的解决方法
%20 %20

以AOP编程方式,我需要的是一个%20超时重新请求的全局功能,%20要在axios.Interceptors下功夫,在github的axios的issue找了别人的一些解决方法,终于找到了一个完成解决方案,就是下面这个。

%20 %20

https://github.com/axios/axios/issues/164#issuecomment-327837467

%20 %20

%20 %20
  1. //在main.js设置全局的请求次数,请求的间隙
  2. axios.defaults.retry%20=%204;
  3. axios.defaults.retryDelay%20=%201000;
  4. axios.interceptors.response.use(undefined,%20function%20axiosRetryInterceptor(err)%20{
  5. %20%20%20%20var%20config%20=%20err.config;
  6. %20%20%20%20//%20If%20config%20does%20not%20exist%20or%20the%20retry%20option%20is%20not%20set,%20reject
  7. %20%20%20%20if(!config%20||%20!config.retry)%20return%20Promise.reject(err);
  8. %20%20%20%20//%20Set%20the%20variable%20for%20keeping%20track%20of%20the%20retry%20count
  9. %20%20%20%20config.__retryCount%20=%20config.__retryCount%20||%200;
  10. %20%20%20%20//%20Check%20if%20we've%20maxed%20out%20the%20total%20number%20of%20retries
  11. %20%20%20%20if(config.__retryCount%20>=%20config.retry)%20{
  12. %20%20%20%20%20%20%20%20//%20Reject%20with%20the%20error
  13. %20%20%20%20%20%20%20%20return%20Promise.reject(err);
  14. %20%20%20%20}
  15. %20%20%20%20//%20Increase%20the%20retry%20count
  16. %20%20%20%20config.__retryCount%20+=%201;
  17. %20%20%20%20//%20Create%20new%20promise%20to%20handle%20exponential%20backoff
  18. %20%20%20%20var%20backoff%20=%20new%20Promise(function(resolve)%20{
  19. %20%20%20%20%20%20%20%20setTimeout(function()%20{
  20. %20%20%20%20%20%20%20%20%20%20%20%20resolve();
  21. %20%20%20%20%20%20%20%20},%20config.retryDelay%20||%201);
  22. %20%20%20%20});
  23. %20%20%20%20//%20Return%20the%20promise%20in%20which%20recalls%20axios%20to%20retry%20the%20request
  24. %20%20%20%20return%20backoff.then(function()%20{
  25. %20%20%20%20%20%20%20%20return%20axios(config);
  26. %20%20%20%20});
  27. });

其他的那个几十个.vue页面的 this.$axios的get 和post 的方法根本就不需要去修改它们的代码。

以下是我做的一个试验。。把axios.defaults.retryDelay = 500, 请求 www.facebook.com

按照惯例,给出源代码,如有更好的建议,请告诉我,谢谢。

http://github.com/ssttm169/use-axios-well

标签:
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

在线投稿:投稿 站长QQ:1888636

后台-插件-广告管理-内容页尾部广告(手机)
关注我们

扫一扫关注我们,了解最新精彩内容

搜索