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

当前回答

为了找到根源问题,我使用XMLHttpRequest而不是获取,并在发送请求后抛出一个异常的消息,告诉实际问题HTTP_1_1_REQUIRED。

显然,react本机(在我的情况下v0.59)只支持http/1.1,然后我在web服务器上禁用了http/2。

如果你的网络服务器是IIS,看看这个问题的答案

希望这能有所帮助。

其他回答

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

在我的例子中,Android模拟器没有连接到Wi-Fi。

看到这里安卓工作室-安卓模拟器Wifi连接没有互联网

这不是答案,而是选择。 我切换到https://github.com/joltup/rn-fetch-blob 它既适用于表单数据,也适用于文件

对于android,在AndroidManifest.xml的应用程序标签中添加android:networkSecurityConfig="@xml/network_security_config",如下所示:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest ... >
        <application android:networkSecurityConfig="@xml/network_security_config"
                        ... >
            ...
        </application>
    </manifest>

Network_security_config.xml文件内容:

<?xml version='1.0' encoding='utf-8'?>
<network-security-config>
<debug-overrides>
    <trust-anchors>
        <!-- Trust user added CAs while debuggable only -->
        <certificates src="user" />
    </trust-anchors>
</debug-overrides>

<!-- let application to use http request -->
<base-config cleartextTrafficPermitted="true" />
</network-security-config>

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

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