在 React Native 中使用 axios 时出现网络错误 [英] Network Error when use axios in React Native
问题描述
这对我来说是一个长期存在的问题,我根本找不到解决方案.
This is long-standing problem for me and I can't find solution at all.
在我的 react native 项目 (react-native-cli) 中,我使用 axios 包向服务器发送请求.但是当我用我的安卓手机进行测试时,它给出了 [错误:网络错误].用模拟器就可以了.
Within my react native project(react-native-cli), I send request to server using axios package. But when I'm testing with my android phone, it gives [Error: Network Error]. With emulator, it's okay.
我确定这不是后端问题,因为我已经对多台服务器进行了测试.我也使用了 fetch 但得到了同样的错误.
I'm sure this is not back-end problem because I've tested with several servers. And I also used fetch instead but got same error.
这是版本信息.
"axios": "^0.19.0",
"react": "16.9.0",
"react-native": "0.61.5",
有时,它也适用于安卓手机.这个问题最大的谜团,困扰了我很久.
Sometimes, it's working on android phone too. This problem is biggest mystery and I suffered for a long time.
遇到这个问题的人,请给我活着.感谢您的仔细阅读.
Somebody who experienced this issue, please alive me. Thank you for careful reading.
有时,即使使用 android 模拟器也无法正常工作.但是在删除原始模拟器并创建新模拟器后,它可以工作了.
const serverUrl = "https://server.com";
axios.post(serverUrl + "/api/candidates/login", {
"email": this.state.email ,
"password": this.state.password
}, {
headers: {
'Content-Type': 'application/json'
}
}).then((response) => {
console.log(response.data);
}).catch((error) => {
console.log(error);
})
推荐答案
我认为这是 http 和 https 请求的问题.所以要启用 https 请求,请尝试以下方法:
I think this is a problem with http and https request. SO to enable https request try the one below :
实现这一点的简单方法是将此属性用于您的 AndroidManifest.xml
,您可以在其中允许所有 http
用于所有请求:
The easy way to implement this is to use this attribute to your AndroidManifest.xml
where you allow all http
for all requests:
android:usesCleartextTraffic="true"
这篇关于在 React Native 中使用 axios 时出现网络错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!