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

当前回答

通过在0.0.0.0上运行模拟服务器 注意:当你使用json-server运行另一个服务器时,这在Expo上有效。

另一种方法是在0.0.0.0而不是localhost或127.0.0.1上运行模拟服务器。

这使得模拟服务器可以在LAN上访问,因为Expo要求开发机器和运行Expo应用程序的移动设备在同一个网络上,所以模拟服务器也可以访问。

在使用json-server时,可以使用以下命令实现这一点

Json-server——host 0.0.0.0——port 8000 ./db。json,看

请访问此链接了解更多信息。

其他回答

对于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>

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

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

React-native Expo和Node Express后端也有同样的问题。这个问题是关于模拟器本地主机和服务器本地主机之间的冲突。您的后端服务器可能运行在127.0.0.1:8000上,但模拟器无法找到这一点。

在终端中使用命令“ipconfig”找到您的ipv4地址。例如,它将是192.138.1.40

在此之后,将其放入fetch ('http://192.138.1.40:8080/')。 同样重要的是—使用相同的主机和端口运行后端服务器。 以Node Express为例:

app.listen(8080, () => console.log("服务器正在运行!"))

这是我的情况下,它显示相同的https请求以及。

重新安装应用程序解决了这个问题。

对我来说……我已经有https了…当我在头文件中添加“Content-type”:“application/json”时,这个问题就消失了

headers: {
  Authorization: token,
  'Content-type': 'application/json',
  /** rest of headers... */
}

平台:安卓