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

当前回答

我在Android模拟器上遇到了同样的问题,在那里我试图使用有效的证书访问外部HTTPS URL。但是在react-native中获取URL失败了

'fetch error:', { [TypeError: Network request failed]
sourceURL: 'http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false' }

1)为了找出日志中的确切错误,我首先在应用程序上使用Cmd + M启用了“远程调试JS”

2)报告的错误为

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

3)我添加的URL的有效证书使用这种方法->步骤2

http://lpains.net/articles/2018/install-root-ca-in-android/

该证书被添加到User选项卡。

4)将属性android:networkSecurityConfig属性添加到AndroidManifest.xml

添加网络安全配置文件 res / xml / network_security_config.xml:

<network-security-config>
    <base-config>
        <trust-anchors>
            <certificates src="user"/>
            <certificates src="system"/>
        </trust-anchors>
    </base-config>
</network-security-config>

这应该工作,并给你一个预期的回应。

其他回答

问题可能出在服务器配置上。

Android 7.0有一个bug。Vicky Chijwani提出的解决方案:

配置您的服务器以使用椭圆曲线prime256v1。为 例如,在Nginx 1.10中,你可以通过设置ssl_ecdh_curve来实现 prime256v1;

我在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://github.com/joltup/rn-fetch-blob 它既适用于表单数据,也适用于文件

只需添加

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

    <application
      android:usesCleartextTraffic="true"

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

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

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