axios请求失败重试请求
axios请求失败重试请求
用于http请求失败异常情况时,自动进行请求重试
1.安装
import axios from 'axios';
import axiosRetry from 'axios-retry';
2.挂载实例
const service = axios.create({
baseURL: "http://127.0.0.1:7002",//配置接口地址
timeout: 20 * 1000,//请求超时时间,单位毫秒(这里配置的20秒)
})
axiosRetry(service, {//传入axios实例
retries: 3, // 设置自动发送请求次数
retryDelay: (retryCount) => {
return retryCount * 1000; // 重复请求延迟(毫秒)
},
shouldResetTimeout: true, // 重置超时时间
retryCondition: (error) => {
console.log("error", error.message)
//true为打开自动发送请求,false为关闭自动发送请求
return true
},
onRetry: function (retryCount,) { //记录执行次数
console.log('err', retryCount)
},
});
3.执行
let s = await service.get('/test') // 第一次请求失败,第二次成功
重试结果:
4.原因
通过查询官网,找到了这是由于axios 1.1.1 and 1.1.3 同时使用时 axios-retry 3.3.1 只能实现单次重试。
详情查看:https://github.com/softonic/axios-retry/issues/213