React Native Native CLI安卓物理设备配置及网络请求异常解决
React Native Native CLI 安卓物理设备网络请求完整配置指南
一、Android 核心配置文件检查与修正
1. AndroidManifest.xml 权限与明文请求配置
确保android/app/src/main/AndroidManifest.xml包含以下配置,注意标签层级:
- 在
<manifest>标签下、<application>标签外添加网络权限:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
- 在
<application>标签内开启明文请求支持并关联网络安全配置:
<application ... android:usesCleartextTraffic="true" android:networkSecurityConfig="@xml/network_security_config" >
2. 网络安全配置文件(network_security_config.xml)
在android/app/src/main/res/xml目录下创建该文件(无xml目录则新建),内容如下:
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <!-- 调试模式下信任所有证书,方便开发测试 --> <debug-overrides> <trust-anchors> <certificates src="system" /> <certificates src="user" /> </trust-anchors> </debug-overrides> <!-- 全局允许明文HTTP请求 --> <base-config cleartextTrafficPermitted="true"> <trust-anchors> <certificates src="system" /> </trust-anchors> </base-config> <!-- 本地服务器/测试域名白名单 --> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">你的本地IP(如192.168.1.100)</domain> <domain includeSubdomains="true">测试服务器域名</domain> </domain-config> </network-security-config>
二、本地网络环境排查
- 确认物理设备与后端服务所在电脑连接同一WiFi网络,禁止混合使用WiFi和手机热点。
- 验证本地IP正确性:电脑执行
ipconfig(Windows)或ifconfig(Mac/Linux),取WiFi的IPv4地址,禁止使用localhost/127.0.0.1(物理设备无法访问)。 - 接口可用性测试:在物理设备浏览器中输入
http://你的本地IP:端口/接口路径,能返回数据则接口正常,否则检查后端服务状态、端口开放情况、电脑防火墙设置。
三、网络请求代码常见问题修正
1. Fetch 请求标准写法
fetch('http://192.168.1.100:3000/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json', // 必须匹配后端接收格式 // 按需添加其他请求头,如Token }, body: JSON.stringify({ username: 'test', password: '123456' }) }) .then(res => { // 非JSON格式接口改用res.text() if (!res.ok) throw new Error(`HTTP错误:${res.status}`) return res.json() }) .then(data => console.log(data)) .catch(err => console.error('请求失败:', err));
2. Axios 替代方案(规避Fetch兼容性问题)
部分RN版本的Fetch存在bug,可换用Axios:
先安装依赖:
npm install axios
请求示例:
import axios from 'axios'; axios.post('http://192.168.1.100:3000/api/login', { username: 'test', password: '123456' }) .then(res => console.log(res.data)) .catch(err => console.error('请求失败:', err));
四、进阶排查点
- 检查RN版本:旧版本(如0.60以下)存在网络请求兼容性问题,建议升级至稳定版。
- 代理设置:若电脑开启全局代理,物理设备需同步配置代理,或关闭代理测试。
- 安卓日志排查:执行
adb logcat命令查看详细网络错误日志,定位证书问题或连接超时原因。
内容的提问来源于stack exchange,提问作者Ankit
相关产品推荐
相关产品推荐

