android - 在 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);
})
解决方案
我认为这是 http 和 https 请求的问题。所以要启用 https 请求,请尝试以下方法:
实现这一点的简单方法是将此属性用于您AndroidManifest.xml
允许http
所有请求的位置:
android:usesCleartextTraffic="true"
推荐阅读
- api - 拆分不适用于翻译的对象
- python - 为单元测试禁用/修补 flask_of_oil OAuthFilter 装饰器
- c# - NetworkStream 在 Unity 中接收到一个空字符串数据
- c# - 订购系统应该如何工作。网页接口
- mod-rewrite - 无法使用 apache http 服务器中 Location 标记中的上下文路径删除 url 中的空参数
- c++ - websocat 是否正确处理与 websocketpp 服务器的关闭握手?
- vaadin - Vaadin 14 - 错误:检测到从 DOM 中删除的容器元素
- azure-devops - 如何在 azure devops 管道中应用 terraform.tfvars
- cloudflare-workers - Cloudflare worker node.js 中的环境变量使用
- c - 为什么我的指针不想被取消引用?