我有一个 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>
最佳答案
我建议您使用 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,
});
};
希望有帮助。如有疑问请放心
关于javascript - 如何使用 React Native 管理 axios 中的 429 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59622160/