Axios使用攔截器全局處理請求重試

Axios攔截器

Axios提供了攔截器的接口,讓咱們可以全局處理請求和響應。Axios攔截器會在Promise的then和catch調用前攔截到。ios

請求攔截示例git

axios.interceptors.request.use(function (config) {
    // 在發起請求請作一些業務處理
    return config;
  }, function (error) {
    // 對請求失敗作處理
    return Promise.reject(error);
  });

響應攔截示例github

axios.interceptors.response.use(function (response) {
    // 對響應數據作處理
    return response;
  }, function (error) {
    // 對響應錯誤作處理
    return Promise.reject(error);
  });

Axios實現請求重試

在某些狀況(如請求超時),咱們可能會但願可以從新發起請求。這時能夠在響應攔截器作下處理,對請求發起重試。axios

請求重試須要考慮三個因素:spa

  1. 重試條件
  2. 重試次數
  3. 重試時延

配置code

axios.defaults.retry = 1; //重試次數
axios.defaults.retryDelay = 1000;//重試延時
axios.defaults.shouldRetry = (error) => true;//重試條件,默認只要是錯誤都須要重試

響應攔截重試接口

axios.interceptors.response.use(undefined, (err) => {
    var config = err.config;
    // 判斷是否配置了重試
    if(!config || !config.retry) return Promise.reject(err);

    if(!config.shouldRetry || typeof config.shouldRetry != 'function') {
       return Promise.reject(err);
    }

    //判斷是否知足重試條件
    if(!config.shouldRetry(err)) {
      return Promise.reject(err);
    }

    // 設置重置次數,默認爲0
    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);
    });
});

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