当前位置: 首页 > news >正文

Axios请求超时重发机制

Axios 超时重新请求实现方案

在 Axios 中实现超时重新请求可以通过以下几种方式:

1. 使用拦截器实现自动重试

import axios from 'axios';// 创建axios实例
const instance = axios.create();// 设置超时时间
instance.defaults.timeout = 5000;// 最大重试次数
const MAX_RETRY = 3;// 添加请求拦截器
instance.interceptors.response.use(undefined, (error) => {const config = error.config;// 如果配置不存在或未设置重试选项,则拒绝if (!config || !config.retry) return Promise.reject(error);// 设置重试次数变量config.__retryCount = config.__retryCount || 0;// 检查是否已达到最大重试次数if (config.__retryCount >= config.retry) {return Promise.reject(error);}// 增加重试计数器config.__retryCount += 1;// 创建新的Promise来处理指数退避const backoff = new Promise((resolve) => {setTimeout(() => {resolve();}, config.retryDelay || 1000);});// 返回Promise,在退避时间后重试请求return backoff.then(() => instance(config));
});// 使用示例
instance.get('/api/data', {retry: MAX_RETRY, // 重试次数retryDelay: 1000 // 重试延迟时间(毫秒)
}).then(response => {console.log(response.data);
}).catch(error => {console.error('请求失败:', error);
});

2. 封装请求函数实现重试

function requestWithRetry(url, options = {}, retryCount = 3) {return new Promise((resolve, reject) => {const attempt = (currentRetry) => {axios({url,...options,timeout: options.timeout || 5000}).then(resolve).catch((error) => {if (currentRetry <= 0 || !isRetryable(error)) {return reject(error);}console.log(`请求失败,剩余重试次数: ${currentRetry - 1}`);// 指数退避const delay = Math.pow(2, retryCount - currentRetry) * 1000;setTimeout(() => {attempt(currentRetry - 1);}, delay);});};attempt(retryCount);});
}// 判断错误是否可重试
function isRetryable(error) {return (error.code === 'ECONNABORTED' || // 超时!error.response || // 无响应(网络错误)error.response.status >= 500 // 服务器错误);
}// 使用示例
requestWithRetry('/api/data', { method: 'get' }, 3).then(response => console.log(response.data)).catch(error => console.error('最终失败:', error));

3. 使用第三方库

也可以使用专门处理重试的库,如 axios-retry:

import axios from 'axios';
import axiosRetry from 'axios-retry';// 配置axios-retry
axiosRetry(axios, {retries: 3, // 重试次数retryDelay: (retryCount) => {return retryCount * 1000; // 重试延迟},retryCondition: (error) => {// 只在超时或5xx错误时重试return axiosRetry.isNetworkOrIdempotentRequestError(error) || error.code === 'ECONNABORTED';}
});// 正常使用axios
axios.get('/api/data', { timeout: 5000 }).then(response => console.log(response.data)).catch(error => console.error('请求失败:', error));

注意事项

  1. 幂等性:确保请求是幂等的(GET、HEAD、OPTIONS、PUT、DELETE等),POST请求重试可能导致重复操作
  2. 退避策略:建议使用指数退避策略,避免同时重试大量请求
  3. 用户体验:对于前端应用,应考虑用户等待时间,不宜设置过多重试次数
  4. 取消请求:如果用户导航离开页面,应取消未完成的请求

以上方案可以根据实际需求进行调整和组合使用。

相关文章:

  • JS手写代码篇---手写函数柯里化
  • 【Python 算法零基础 4.排序 ⑪ 十大排序算法总结】
  • 浏览器工作原理01 [#]Chrome架构:仅仅打开了1个页面,为什么有4个进程
  • 汽车的安全性能测试:试验台铁地板的重要性
  • Unity3D仿星露谷物语开发60之定制角色其他部位
  • 【题解-洛谷】P3370 【模板】字符串哈希
  • Docker + Nginx + Logrotate 日志管理与轮换实践
  • YUM仓库编译出现`conflicting requests`问题解决方案
  • Linux系统安装Docker
  • Python 构建法律DeepSeek RAG
  • YOLO训练保持原有识别能力
  • Spring 团队详解:AOT 缓存实践、JSpecify 空指针安全与支持策略升级
  • 宝塔think PHP8 安装使用FFmpeg 视频上传
  • 数据结构之常用排序算法(冒泡、选择等)
  • 以STM32H7微控制器为例,简要说明stm32h7xx_it.c的作用
  • 主流 AI IDE 之一的 Cursor 介绍
  • mysql+keepalived
  • C#中的CLR属性、依赖属性与附加属性
  • 《零基础读懂新能源汽车》—— 新能源汽车充电革命:从逆变器原理到800V超充实战,一篇全掌握!
  • Python训练营打卡Day46(2025.6.6)
  • 遵义城乡建设网站/百度 个人中心首页
  • 用dreamwever做网站/百度关键词收费标准
  • 永久免费建网站/aso关键词覆盖优化
  • 香港股市的做空网站/信息流优化师简历怎么写
  • 最佳网站/seo发外链的网站
  • 厦门酒店团购网站建设/推广赚钱的平台有哪些