当我使用react-native init (RN版本0.29.1)创建一个全新的项目,并在渲染方法中获取公共facebook演示电影API时,它抛出了一个网络请求失败。有一个非常无用的堆栈跟踪,我不能调试网络请求在chrome控制台。这是我发送的fetch:

fetch('http://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        return responseJson.movies;
      })
      .catch((error) => {
        console.error(error);
      });

当前回答

React Native Docs给出了这个问题的答案。

苹果已经阻止隐式明文HTTP资源加载。所以我们需要添加以下我们的项目的信息。Plist(或等效)文件。

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

测试您的集成->添加应用程序传输安全例外

其他回答

React Native Docs给出了这个问题的答案。

苹果已经阻止隐式明文HTTP资源加载。所以我们需要添加以下我们的项目的信息。Plist(或等效)文件。

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

测试您的集成->添加应用程序传输安全例外

只需添加

<uses-permission android:name="android.permission.INTERNET" />

    <application
      android:usesCleartextTraffic="true"

然后将获取URL域(localhost)替换为您的IP地址,

const dataRaw = await fetch('http://192.168.8.102:4000');

检查您的SSL是否正确配置,将url放在这里。

我在Android上也遇到了同样的问题,但我设法找到了解决方案。Android默认从API Level 28开始就屏蔽明文流量(非http请求)。然而,react-native在调试版本(android/app/src/debug/res/xml/react_native_config.xml)中添加了一个网络安全配置,它定义了一些域(localhost,以及AVD / Genymotion的主机ip),可以在dev模式下使用,无需SSL。 您可以在那里添加您的域以允许http请求。

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
  <domain-config cleartextTrafficPermitted="true">
    <domain includeSubdomains="false">localhost</domain>
    <domain includeSubdomains="false">10.0.2.2</domain>
    <domain includeSubdomains="false">10.0.3.2</domain>
    <domain includeSubdomains="true">dev.local</domain>
  </domain-config>
</network-security-config>

如果您正在连接到HTTPS网站,请检查您的模拟器的互联网连接。(在我的情况下,我使用的是通过USB连接的手机模拟器,它的互联网是离线的)