状态为200且数据为空时,Axios拦截器重试http请求 [英] Axios interceptor retry http request when status is 200 and data is empty

查看:455
本文介绍了状态为200且数据为空时,Axios拦截器重试http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在短暂轮询一个端点,直到准备好一些数据为止,我想最多重试该请求10次.

I am short polling an endpoint until some data is ready i would like to retry the request up to 10 times.

当数据还没有准备好时,我会收到一个200,其中包含一个空数组.

When the data is not ready i recieve a 200 with an empty array.

数据准备好后,我将收到一个非空数组200.

When the data is ready i recieve a 200 with a non-empty array.

我使用以下库 https://github.com/axios/axios https://github.com/softonic/axios-retry

 try {

   const axiosInstance = axios.create();

   axiosInstance.interceptors.response.use((response) => {

     if (response.data.metrics.length === 0) {
       const error = new Error("Metrics Not Ready");
       return Promise.reject(error);

     }
     return response;
   }, (error) => {
     return Promise.reject(error);
   });

   axiosRetry(axiosInstance, {
     retries: 10,
     retryCondition: (error) => {
       console.log("RETRY CONDITION", error);
     },
   });

   const metrics = await axiosInstance(options);

 } catch (error) {
   console.log(error);
 }

我创建了一个axios拦截器,以检查数组的长度(如果0引发错误).但是,axiosRetry并没有抓住这一点,在这一点上我想重试该请求.相反,它被捕获在try catch块中并结束.

I have created an axios interceptor to check the length of the array if its 0 i am throwing an error. However this does not get caught by axiosRetry which at this point i want to retry the request. Instead it is being caught in the try catch block and ends.

推荐答案

您不需要axios-retry,只需要axios及其响应拦截器即可,并执行以下步骤:

You don't need axios-retry, all you need is axios and its response interceptor, with following steps:

  1. 检查数据是否为空.如果是,则抛出axios.Cancel错误.这将取消请求,调用错误处理程序而不是成功处理程序.
  2. 在错误处理程序中,如果我们没有超过最大重试次数(在您的情况下为10),则重新发送HTTP请求.
  3. 继续执行第1步和第2步,直到获得数据或重试10次为止.
  1. Check whether data is empty. If yes, throw an axios.Cancel error. This would cancel the request, invoking error handler instead of success handler.
  2. In the error handler, re-send the HTTP request if we haven't exceeded the maximum retry number (in your case, it is 10).
  3. Keep running step 1 and 2 until we get data or have retried 10 times.

代码如下:

const axios = require('axios');

const MAX_RETRY = 10;
let currentRetry = 0;

function successHandler() {
  console.log('Data is Ready');
}

function errorHandler() {
  if (currentRetry < MAX_RETRY) {
    currentRetry++;
    console.log('Retrying...');
    sendWithRetry();
  } else {
    console.log('Retried several times but still failed');
  }
}

function sendWithRetry() {
  axios.get('http://example.com')
    .then(successHandler).catch(errorHandler);
}

axios.interceptors.response.use(function (response) {
  if (response.data.metrics.length) {
    throw new axios.Cancel('Operation canceled by the user.');
  } else {
    return response;
  }
}, function (error) {
  return Promise.reject(error);
});

sendWithRetry();

不幸的是,对于axios-retry,当响应状态为200 OK时,您无法重试HTTP请求,因为axios-retry使用axios.interceptors.response.use,但对成功的响应"不执行任何操作.

For axios-retry, unfortunately you cannot retry HTTP request when response status is 200 OK, as axios-retry uses axios.interceptors.response.use but does nothing for "successful response".

这是axios-retry的源文件es/index.js中的相应代码.您可以看到成功响应的拦截器是null:

Here is the corresponding code in axios-retry's source file es/index.js. You can see that the interceptor of successful response is null:

export default function axiosRetry(axios, defaultOptions) {
  axios.interceptors.request.use(config => {
    const currentState = getCurrentState(config);
    currentState.lastRequestTime = Date.now();
    return config;
  });

  axios.interceptors.response.use(null, error => {
    const config = error.config;

    // If we have no information to retry the request
    if (!config) {
      return Promise.reject(error);
    }
    ....

这篇关于状态为200且数据为空时,Axios拦截器重试http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆