网络安全配置导致React Native应用程序无法连接到Metro服务器

nbysray5  于 2023-08-07  发布在  React
关注(0)|答案(2)|浏览(160)

我有一个很奇怪的问题,我无法解决。我也不知道如何在谷歌上搜索,因为虽然我熟悉React Native,但我不熟悉Android本身,也不知道我的搜索词应该是什么。
因此,在我的react本机代码中,我的客户端在android/app/src/main/res/xml路径下添加了以下network_security_config.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">_my_clients_ip</domain>
    </domain-config>
</network-security-config>

字符串
因此,他们在android/app/src/main路径的AndroidManifest.xml文件中添加了以下内容:

.
.
<application
.
.
        android:networkSecurityConfig="@xml/network_security_config"
</application>
.
.


上面的点表示其他属性和标记,为了简洁起见,我省略了它们。

我的问题

我正在使用Android模拟器来测试我的React Native应用程序。
在上面的xml不存在之前,我的react native应用程序运行良好。然而,有了上面的附加功能,当我使用命令(在2个不同的终端中)启动我的react原生应用程序时:

$ npx react-native start --reset-cache
$ npx react-native run-android


应用程序加载在模拟器中-但它似乎与地铁捆绑器断开连接(运行npx react-native start --reset-cache的终端)。
我尝试在此终端中按r键以检查重新加载是否有效,并输出:

warn No apps connected. Sending "reload" to all React Native apps failed.
Make sure your app is running in the simulator or on a phone connected via USB.


我不知道为什么。如果我从AndroidManifest.xml中删除android:networkSecurityConfig="@xml/network_security_config",那么一切都很好。
我该如何解决这个问题?

iih3973s

iih3973s1#

您可以尝试将localhost域添加到XML文件中:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">_my_clients_ip</domain>
        <domain includeSubdomains="true">127.0.0.1</domain>
        <domain includeSubdomains="true">10.0.0.1</domain>
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

字符串

1rhkuytd

1rhkuytd2#

您可以尝试将localhost域添加到XML文件中:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">_my_clients_ip</domain>
        <domain includeSubdomains="true">127.0.0.1</domain>
        <domain includeSubdomains="true">10.0.0.1</domain>
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

字符串
你好,朋友,谢谢你的建议,我正在经历同样的问题,它帮助我理解发生了什么。

解决方案

我猜,由于metro服务器在本地通过HTTP协议运行,您应该允许ip地址10.0.2.2(主机别名https://developer.android.com/studio/run/emulator-networking)并设置cleartextTrafficPermitted="true",这将是结果:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

提示

由于我使用的是flavours,我还决定将上述解决方案放在文件夹src/debug/xml/network_security_config.xml中,这样10.0.2.2就只允许在调试模式下使用。

相关问题