Javascript 如何使用react native管理axios中的429个错误?

Javascript 如何使用react native管理axios中的429个错误?,javascript,node.js,react-native,express,axios,Javascript,Node.js,React Native,Express,Axios,我有一个react原生应用程序,它使用MongoDB作为数据库,使用express和node js,我还使用Axios与客户端和服务器通信 现在,应用程序不断快速地从数据库发送和接收数据,例如,当应用程序正在使用时,用户每秒向后端发出多达3到4个请求 一切正常,但有很多429个错误,如何处理这个错误或防止它发生,而不损害用户体验很多 下面是axios实例 const instance = axios.create({ baseURL: 'http://9rv324283.ngrok.io' })

我有一个react原生应用程序,它使用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>
{
试一试{
const response=wait instance.get('fetchnewdisks');
this.setState({data:response.data})
}捕捉(错误){
console.log(错误)
}
}}>
下面是将数据发送到数据库

<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>
instance.patch(`/postNewDish/${this.state.dish}`)}>
驿站

我建议您使用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,
  });
};

希望能有帮助。无需怀疑

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


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

我曾尝试过使用此方法,它总是返回错误429,设置为5(秒),并使用以下方法得出此结果:


我正在努力将此添加到axios retry中,您一分钟发送多少请求?429是节流错误。大约10到15@BoraSumerI我想我看到了,你忘记在函数中添加async以等待工作。好的,使用axios拦截器很好,但这将如何解决问题?