axios 添加重试功能

一、 axios 如何实现重试

参考链接: axios 如何实现重试

二、案例代码

service.js

import axios from 'axios';
import { getLocationParams } from './packagFunc';
/** start */
let IdToken = '';
/**
 * get several cases of  token
 * ?token=xxx&iothub_id=xxx
 * ?iothub_id=xxx&token=xxx
 * #{{token}}
 */
if (window.location.href.indexOf('?') !== -1 || window.location.href.indexOf('#') !== -1) {
  if (window.location.href.split('?')[1]) {
    IdToken = getLocationParams().token;
  } else {
    const hashParams = window.location.href.split('#')[1].split('&')
      ? window.location.href.split('#')[1].split('&')[0] : window.location.href.split('#')[1];
    const tokenArr = getLocationParams().token ? getLocationParams().token : hashParams;
    IdToken = tokenArr;
  }

  localStorage.setItem('IdToken', IdToken);
  window.location.href = window.location.pathname;
} else if (localStorage.getItem('IdToken')) {
  IdToken = localStorage.getItem('IdToken');
}
/**  end */

/**
 * Configure the adapter for the axios to realise the retry function when the response is fail
 * @param {*} adapter
 * @param {*} options
 * @returns
 */
function retryAdapterEnhancer(adapter, options) {
  const { times = 1, delay = 3000 } = options;

  return async (config) => {
    const { retryTimes = times, retryDelay = delay } = config;
    let retryCount = 0;

    const request = async () => {
      try {
        return await adapter(config);
      } catch (err) {
        // Only retry once
        if (!retryTimes || retryCount >= retryTimes) {
          return Promise.reject(err);
        }

        retryCount += 1;
        // delay process
        const delayFunc = new Promise((resolve) => {
          setTimeout(() => {
            resolve();
          }, retryDelay);
        });
        // send the request again
        return delayFunc.then(() => request());
      }
    };
    return request();
  };
}

const service = axios.create({
  baseURL: '',
  adapter: retryAdapterEnhancer(axios.defaults.adapter, {
    retryDelay: 3000,
  }),
  // timeout: 5000,
});

/**
 * Request interceptors
 */
service.interceptors.request.use(
  (config) => {
    const configParam = config;
    if (IdToken) {
      configParam.headers.Authorization = `Bearer ${IdToken}`;
    }
    return configParam;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  },
);

/**
 * Response interceptors
 */
service.interceptors.response.use(
  (response) => {
    const res = response;
    if (res.status === 200 || res.status === 201) {
      return res;
    }
    return Promise.reject(new Error('Error'));
  },
  (error) => {
    console.log('err', error);
    return Promise.reject(error);
  },
);

export default service;

你可能感兴趣的:(React,Vue,javascript,前端,vue.js)