添加android:networkSecurityConfig致React Native安卓启动失败求助
React Native添加networkSecurityConfig后启动失败的原因与解决办法
原因分析
- 网络安全配置过于严格,阻断了Metro本地服务器请求:开发模式下React Native应用依赖本地Metro服务器加载JS脚本,若你的
network_security_config.xml仅允许特定域名访问,会拒绝Android模拟器的本地回环地址(如10.0.2.2)或localhost的请求,导致脚本加载失败。 - 配置文件存在语法错误:
network_security_config.xml的标签未闭合、属性拼写错误等问题,会导致AndroidManifest解析失败,间接引发脚本加载报错。
解决办法
- 调整网络安全配置,兼容开发环境
修改res/xml/network_security_config.xml,添加调试环境的规则,允许本地Metro请求,同时保留目标不受信任网站的配置:<?xml version="1.0" encoding="utf-8"?> <network-security-config> <!-- 调试模式下允许本地请求和用户证书 --> <debug-overrides> <trust-anchors> <certificates src="user" /> </trust-anchors> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">10.0.2.2</domain> <domain includeSubdomains="true">localhost</domain> </domain-config> </debug-overrides> <!-- 生产环境配置目标不受信任网站 --> <domain-config> <domain includeSubdomains="true">你的目标域名</domain> <trust-anchors> <certificates src="user" /> </trust-anchors> </domain-config> </network-security-config> - 检查配置文件语法
确认network_security_config.xml中所有标签正确闭合,属性名称拼写无误(比如cleartextTrafficPermitted不要写错)。 - 验证文件路径与引用
确保network_security_config.xml确实放在res/xml目录下,AndroidManifest中的引用路径@xml/network_security_config完全匹配。 - 确认打包状态
若为生产打包场景,确保index.android.bundle已正确生成并放置在assets目录;开发场景下,先启动Metro服务(执行npx react-native start)再运行应用。
内容的提问来源于stack exchange,提问作者famfamfam
相关产品推荐
相关产品推荐

