【问题标题】:Network Security Config results in React Native app not connecting to metro server网络安全配置导致 React Native 应用程序未连接到 Metro 服务器
【发布时间】:2021-04-20 16:25:27
【问题描述】:

我有一个非常奇怪的问题,我无法解决。我也不知道怎么用谷歌搜索这个,因为虽然我熟悉 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>

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

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

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

我的问题

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

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

应用程序在模拟器中加载 - 但它似乎与 Metro bundler 断开连接(终端运行 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",那么一切都很好。

我该如何解决这个问题?

【问题讨论】:

    标签: android react-native metro-bundler


    【解决方案1】:

    您可以尝试将 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>
    

    【讨论】:

      猜你喜欢
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      相关资源
      最近更新 更多