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

查看:25
本文介绍了状态为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/axioshttps://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天全站免登陆