You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用retry-axios实现重试机制遇问题:仅重试一次且报头部错误

解决retry-axios重试次数异常与头部错误问题

问题分析

  • 重试仅执行一次:默认retry-axios的重试条件不包含400/500状态码,需自定义触发规则。
  • Invalid character in header content ["0"]:重试过程中请求头被注入非字符串值(如数字0),需修复头部格式问题。

解决方案代码

const axios = require('axios');
const rax = require('retry-axios');

const baseUrl = `https://mock.codes/500`;
const myAxiosInstance = axios.create();

myAxiosInstance.defaults.raxConfig = {
    retry: 5,
    retryDelay: 5000,
    backoffType: 'static',
    instance: myAxiosInstance,
    // 自定义重试触发条件:仅匹配400或500状态码
    shouldRetry: (err) => {
        const cfg = rax.getConfig(err);
        if (err.response && (err.response.status === 400 || err.response.status === 500)) {
            return true;
        }
        // 保留网络类错误的默认重试逻辑(可选)
        return rax.shouldRetry(err);
    },
    onRetryAttempt: (err) => {
        const cfg = rax.getConfig(err);
        console.log(`Retry attempt #${cfg.currentRetryAttempt}`);
    }
};

// 添加请求拦截器,修复头部非字符串格式问题
myAxiosInstance.interceptors.request.use((config) => {
    if (config.headers) {
        Object.keys(config.headers).forEach(key => {
            if (typeof config.headers[key] !== 'string') {
                config.headers[key] = String(config.headers[key]);
            }
        });
    }
    return config;
});

const interceptorId = rax.attach(myAxiosInstance);

// 异步执行请求
async function fetchData() {
    try {
        const res = await myAxiosInstance.get(baseUrl);
        console.log('请求成功:', res.data);
    } catch (err) {
        console.error('最终请求失败:', err.message);
    }
}

fetchData();

关键修改说明

  1. 自定义shouldRetry函数:精准指定仅在响应状态码为400或500时触发重试,同时保留默认的网络错误重试逻辑(如超时、DNS失败等)。
  2. 请求头格式修正:通过拦截器强制将所有请求头值转为字符串,避免重试时因非字符串头部引发的格式错误。
  3. 完善异步流程:将请求逻辑封装进异步函数,确保await语法正确生效。

内容的提问来源于stack exchange,提问作者Sufail Kalathil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 04:20:26