【问题标题】:How to manage 429 errors in axios with react native?如何使用 react native 管理 axios 中的 429 错误?
【发布时间】:2020-01-07 04:26:41
【问题描述】:

我有一个 react native 应用程序,它使用 MongoDB 作为数据库,带有 express 和 node js 我还使用 Axios 与客户端与服务器通信

现在应用不断地从数据库快速发送和接收数据,例如,当应用在使用时,用户每秒向后端发出多达 3 到 4 个请求,

一切正常,但有很多 429 错误,如何在不影响用户体验的情况下处理此错误或防止其发生?

下面是axios实例

const instance = axios.create({ baseURL: 'http://9rv324283.ngrok.io' })

下面是从数据库中获取数据

<NavigationEvents
onWillFocus={() => {

  try {

    const response = await instance.get('fetchNewDishes');

    this.setState({data: response.data})

  } catch(err) {

    console.log(err)

  }

}}>

下面是向数据库发送数据

<TouchableOpacity onPress={() =>  instance.patch(`/postNewDish/${this.state.dish}`)}>
            <Text style={{ fontSize: 16, color: '#555', padding: 15 }}>Post Dish</Text>
  </TouchableOpacity>

【问题讨论】:

  • 一分钟发送多少请求? 429 是限制错误。
  • 大约 10 到 15 @BoraSumer
  • 我想我明白了,你忘了在你的函数中添加 async 以便等待工作。

标签: javascript node.js react-native express axios


【解决方案1】:

我建议您使用 axios 拦截器来实际跟踪 axios 中的错误处理,请参见下面的示例:

import ax from 'axios';
import {config} from '../global/constant';

const baseUrl = config.apiUrl;

let axios = ax.create({
  baseURL: baseUrl,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    'Access-Control-Allow-Origin': '*',
  },
});

axios.interceptors.request.use(req => handleRequest(req));
axios.interceptors.response.use(
  res => handleResponse(res),
  rej => handleError(rej),// here if its an error , then call handleError and do what you want to do with error.
);

// sending the error as promise.reject
const handleError = error => {
  let errorResponse = {...error};
  console.log({...error}, 'error');
  return Promise.reject({
    data: errorResponse.response.data,
    code: errorResponse.response.status,
  });
};

希望对您有所帮助。如有疑问,请随意

【讨论】:

  • 好吧,使用 axios 拦截器很好,但是这将如何解决问题呢?
【解决方案2】:

您可以控制后端吗?可能存在限制请求的中间件,例如express-rate-limit

确保禁用这些中间件,或者在中间件配置中每分钟允许更多请求。

【讨论】:

    【解决方案3】:

    我使用https://httpstat.us/429/cors 解决了这个问题,它总是返回错误 429,retry-after 设置为 5(秒),然后使用 axios-retry 想出了这个:

    import axios from "axios";
    import axiosRetry from "axios-retry";
    
    let instance = axios.create({ baseURL: "https://httpstat.us" });
    
    axiosRetry(instance, {
      retryCondition: (e) => {
        return (
          axiosRetry.isNetworkOrIdempotentRequestError(e) ||
          e.response.status === 429
        );
      },
      retryDelay: (retryCount, error) => {
        if (error.response) {
          const retry_after = error.response.headers["retry-after"];
          if (retry_after) {
            return retry_after;
          }
        }
    
        // Can also just return 0 here for no delay if one isn't specified
        return axiosRetry.exponentialDelay(retryCount);
      }
    });
    
    // Test for error 429
    instance({
      url: "/429/cors",
      method: "get"
    })
      .then((res) => {
        console.log("429 res: ", res);
      })
      .catch((e) => {
        console.log("429 e: ", e);
      });
    
    // Test to show that code isn't triggered by working API call
    instance({
      url: "/200/cors",
      method: "get"
    })
      .then((res) => {
        console.log("200 res: ", res);
      })
      .catch((e) => {
        console.log("200 e: ", e);
      });
    

    我正在为https://github.com/softonic/axios-retry/issues/72 正确地将其添加到 axios-retry 中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多