添加android:networkSecurityConfig后React Native调试构建失败
解决React Native添加网络安全配置后无法加载脚本的问题
核心原因
你的网络安全配置仅允许了xxx域名的明文流量,但React Native调试时需要连接本地Metro服务器(通常是10.0.2.2、localhost或电脑局域网IP),这些地址不在允许列表中,导致无法加载脚本。
修复步骤
1. 更新debug环境的网络安全配置
修改app/src/debug/xml/network_security_config.xml,添加本地调试所需的域名:
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <!-- 允许业务域名的明文流量 --> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">xxx</domain> <!-- 添加本地调试地址 --> <domain includeSubdomains="true">10.0.2.2</domain> <!-- 模拟器默认本地回环地址 --> <domain includeSubdomains="true">localhost</domain> <domain includeSubdomains="true">你的电脑局域网IP</domain> <!-- 例如192.168.1.100 --> </domain-config> <!-- 调试环境全局允许明文流量(生产环境请勿放开) --> <base-config cleartextTrafficPermitted="true"> <trust-anchors> <certificates src="system" /> </trust-anchors> </base-config> </network-security-config>
2. 确认debug配置引用正确
检查app/src/debug/AndroidManifest.xml的application标签,确保已添加:
android:networkSecurityConfig="@xml/network_security_config"
3. 清理并重新构建项目
执行以下命令:
cd android ./gradlew clean cd .. npx react-native run-android
4. 确保Metro服务器正常运行
如果Metro未启动,执行命令启动:
npx react-native start
额外提示
生产环境的app/src/main/res/xml/network_security_config.xml无需添加本地调试地址,保持原有配置即可,避免安全风险。
内容的提问来源于stack exchange,提问作者Huan Huynh
相关产品推荐
相关产品推荐

