如何使用axios-retry对出现5XX错误的POST请求进行重试?
解决axios-retry对POST请求5XX错误重试的问题
问题原因
axios-retry默认仅对幂等请求方法(如GET、HEAD、OPTIONS)进行重试,POST方法不在默认重试列表中,因此即使遇到5XX服务器错误也不会触发重试逻辑。
解决方案
方案1:将POST加入允许重试的方法列表
直接配置retryMethods,把POST包含进去,这样所有POST请求遇到可重试错误时都会触发重试:
import axiosRetry from 'axios-retry'; axiosRetry(axios, { retries: 3, // 扩展重试方法列表,加入POST retryMethods: ['GET', 'HEAD', 'OPTIONS', 'POST'] }); axios.post('http://localhost:3005/post', {name: "abc"}) .then(result => { console.log(result.data); // 'ok' });
方案2:自定义重试条件(更安全)
如果不想让所有POST请求都重试,仅针对5XX错误的POST请求重试,可以通过retryCondition自定义判断逻辑:
import axiosRetry from 'axios-retry'; axiosRetry(axios, { retries: 3, retryCondition: (error) => { // 判断是否为POST请求且返回5XX状态码 const isPostWithServerError = error.config.method === 'post' && error.response && error.response.status >= 500 && error.response.status < 600; // 保留默认的重试条件(网络错误、幂等请求的服务器错误等),加上POST的5XX情况 return axiosRetry.defaultRetryCondition(error) || isPostWithServerError; } }); axios.post('http://localhost:3005/post', {name: "abc"}) .then(result => { console.log(result.data); // 'ok' });
注意事项
POST请求若不是幂等接口(重复提交会导致重复创建资源、重复扣费等副作用),请谨慎开启重试,避免引发业务异常。
内容的提问来源于stack exchange,提问作者Nagendra Kumar
相关产品推荐
相关产品推荐

