有时候因项目需求,要在接口请求超时或者获取数据失败时,重新请求1次,或者更多次。具体的配置步骤和方法如下:
因为是要在请求超时或者获取数据失败时,进行重新请求设置,那么我们肯定是要在请求返回拦截器里面设置,
import axios from "axios";const Axios = axios.create({ // 下面两个属性,用来设置,请求失败或者超时,自动重新请求的次数和间隙时间retry: 2, // 请求次数retryInterval: 1000 // 求期间隙......});//请求前拦截Axios.interceptors.request.use(config => {return config},function(error) {return Promise.reject(error)});//请求后返回数据拦截Axios.interceptors.response.use(res => {return res},function axiosRetryInterceptor(res) {var config = res.config;//如果配置不存在或重试属性未设置,抛出promise错误if (!config || !config.retry) return Promise.reject(res);//设置一个变量记录重新请求的次数config.retryCount = config.retryCount || 0;// 检查重新请求的次数是否超过我们设定的请求次数if (config.retryCount >= config.retry) {return Promise.reject(res);}//重新请求的次数自增config.retryCount += 1;// 创建新的Promise来处理重新请求的间隙var back = new Promise(function(resolve) {console.log("接口"+config.url+"请求超时,重新请求")setTimeout(function() {resolve();}, config.retryInterval|| 1);});//返回axios的实体,重试请求return back.then(function() {return Axios(config);});});export default Axios