当我使用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);
      });

当前回答

不建议允许http的所有域。 只对必要的域进行例外处理。

来源:在iOS 9和OSX 10.11中配置应用程序传输安全例外

将以下内容添加到信息中。你的应用的Plist文件:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

其他回答

在我的情况下,我有https url,但取回返回网络请求失败的错误,所以我只是stringify的身体,它的工作乐趣

fetch (https://mywebsite.com/endpoint/, { 方法:“文章”, 标题:{ 接受:application / json, “内容类型”:“application / json” }, 身体:JSON.stringify ({ firstParam:“yourValue”, secondParam:“yourOtherValue” }) });

这里的问题是iOS默认不允许HTTP请求,只允许HTTPS。如果你想启用HTTP请求,添加到你的info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

对于Android设备,进入您的项目根文件夹并运行命令:

adb reverse tcp:[your_own_server_port] tcp:[your_own_server_port]

例如:adb reverse tcp:8088 tcp:8088

这将使您的物理设备(即。Android手机)监听本地主机服务器运行在您的开发机器(即您的计算机)地址http://localhost:[your_own_server_port]。

之后,你可以直接在react-native fetch()调用中使用http:localhost:[your_port] /your_api。

不建议允许http的所有域。 只对必要的域进行例外处理。

来源:在iOS 9和OSX 10.11中配置应用程序传输安全例外

将以下内容添加到信息中。你的应用的Plist文件:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

我在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>