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

cal*_*tie 13 android react-native metro-bundler

我有一个非常奇怪的问题,我无法解决。我也不知道如何谷歌这个,因为虽然我熟悉 React Native,但我不熟悉 Android 本身,也不知道我的搜索词应该是什么。

network_security_config.xml因此,在我的 React Native 代码中,我的客户端在路径下添加了以下文件android/app/src/main/res/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>
Run Code Online (Sandbox Code Playgroud)

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

.
.
<application
.
.
        android:networkSecurityConfig="@xml/network_security_config"
</application>
.
.
Run Code Online (Sandbox Code Playgroud)

上面的点表示其他属性和标签,为简洁起见,我省略了这些属性和标签。

我的问题

我正在使用 Android 模拟器来测试我的 React Native 应用程序。
在上面的 xml 不存在之前,我的 React Native 应用程序运行良好。但是,通过上述添加,当我使用命令启动我的 React Native 应用程序时(在 2 个不同的终端中):

$ npx react-native start --reset-cache
$ npx react-native run-android
Run Code Online (Sandbox Code Playgroud)

该应用程序在模拟器中加载 - 但它似乎与metro捆绑器断开连接(终端运行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.
Run Code Online (Sandbox Code Playgroud)

我不知道为什么。android:networkSecurityConfig="@xml/network_security_config"如果我从 中删除AndroidManifest.xml,那么一切都很好。

我该如何解决这个问题?

小智 5

您可以尝试将 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>
Run Code Online (Sandbox Code Playgroud)