首页 > 解决方案 > 在 React Native 中使用 axios 时出现网络错误

问题描述

这对我来说是长期存在的问题,我根本找不到解决方案。

在我的 react native 项目(react-native-cli)中,我使用 axios 包向服务器发送请求。但是当我用我的安卓手机进行测试时,它给出了[错误:网络错误]。用模拟器就好了。

我确定这不是后端问题,因为我已经用多台服务器进行了测试。而且我也使用了 fetch 但得到了同样的错误。

这是版本信息。

"axios": "^0.19.0",
"react": "16.9.0",
"react-native": "0.61.5",

有时,它也适用于安卓手机。这个问题是最大的谜,我受了很长时间。

经历过这个问题的人,请让我活着。感谢您的仔细阅读。

有时,即使使用 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);
        })

标签: androidreact-nativemobileaxiosreact-native-android

解决方案


我认为这是 http 和 https 请求的问题。所以要启用 https 请求,请尝试以下方法:

实现这一点的简单方法是将此属性用于您AndroidManifest.xml允许http所有请求的位置:

android:usesCleartextTraffic="true"

推荐阅读