Vue 结合 Axios 接口超时统一处理

4,486 阅读3分钟

关注公众号: 微信搜索 前端工具人 ; 收货更多的干货

开篇

当网路慢的时候;又或者公司服务器不在内地的时候,接口数据请求不回来超时报错的情况相信大家肯定遇到过的,这里我把我公司项目请求超时的处理方法分享下,希望看过后有帮助。

axios 基本用法就不多说了,详情直戳: https://www.kancloud.cn/yunye/axios/234845

主要是思路: 对 axios 请求拦截器下功夫

步骤

解决方案一:

缺点:

  1. 只重新请求1次,如果再超时的话,它就停止了,不会再请求;
  2. 后台只允许你重新发起一次请求(不能给服务器增压、浪费带宽无限请求)

看了看axios的源代码,超时后, 会在拦截器那里 axios.interceptors.response 捕抓到错误信息, 且 error.code = "ECONNABORTED"


// 请求超时
request.ontimeout = function handleTimeout() {
  reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', request));
  // 取消请求
  request = null;
};

全局超时处理方案:

// 请求拦截器
axios.interceptors.response.use(function(response){
    // 请求成功处理回调
}, function(error){
    // 请求失败、错误处理回调
    var originalRequest = error.config; 
    if(error.code == 'ECONNABORTED' && error.message.indexOf('timeout')!=-1 && !originalRequest._retry){
       originalRequest._retry = true
       return axios.request(originalRequest);
    }
});

解决方法二:推荐

//在main.js设置全局的请求次数,请求的间隙
axios.defaults.retry = 4;
axios.defaults.retryDelay = 1000;
axios.interceptors.response.use(undefinedfunction axiosRetryInterceptor(err) {
 var config = err.config;
 // 如果config不存在或未设置重试选项,请拒绝
 if(!config || !config.retryreturn Promise.reject(err);
 // 设置变量跟踪重试次数
 config.__retryCount = config.__retryCount || 0;
 // 检查是否已经达到最大重试总次数
 if(config.__retryCount >= config.retry) {
  // 抛出错误信息
  return Promise.reject(err);
 }
 // 增加请求重试次数
 config.__retryCount += 1;
 // 创建新的异步请求
 var backoff = new Promise(function(resolve) {
  setTimeout(function() {
   resolve();
  }, config.retryDelay || 1);
 });
 // 返回axios信息,重新请求
 return backoff.then(function() {
  return axios(config);
 });
});

使用:

axios.get('/some/endpoint', { retry: 5, retryDelay: 1000 })
    .then(function(res) {
        console.log('success', res.data);
    })
    .catch(function(err) {
        console.log('failed', err);
    });

配置参数:

  • retry :第一次失败请求后重试请求的次数。
  • retryDelay: 失败请求之间等待的毫秒数(默认为1)。上述就是请求超时处理的的方案了。

扩展 axios 自定义配置新建一个 axios 实例 请求配置信息 Requst Config 以下是开发常用的一些配置选项

axios.create([config])
var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

config配置:

//新建 config.js
import Qs from 'qs'
{
 //请求的接口,在请求的时候,如axios.get(url,config);这里的url会覆盖掉config中的url
 url: '/user',
 // 请求方法同上
 method: 'get'// default
 // 基础url前缀
 baseURL: 'https://some-domain.com/api/',   
 transformRequest: [function (data) {
   // 这里可以在发送请求之前对请求数据做处理,比如form-data格式化等,这里可以使用开头引入的Qs(这个模块在安装axios的时候就已经安装了,不需要另外安装)
  data = Qs.stringify({});
  return data;
 }],
 transformResponse: [function (data) {
  // 这里提前处理返回的数据
  return data;
 }],
 // 请求头信息
 headers: {'X-Requested-With''XMLHttpRequest'},
 //parameter参数
 params: {
  ID: 12345
 },
 //post参数,使用axios.post(url,{},config);如果没有额外的也必须要用一个空对象,否则会报错
 data: {
  firstName: 'Fred'
 },
 //设置超时时间
 timeout: 1000,
 //返回数据类型
 responseType: 'json'// default
}

结尾

文章来源:自己博客文章 https://www.cnblogs.com/ljx20180807/p/9921347.html