当我使用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上也遇到了同样的问题,但我设法找到了解决方案。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>

其他回答

对于我们来说,这是因为我们正在上传一个文件,而RN filePicker没有给出正确的mime类型。它只是给了我们image作为类型。我们需要将其更改为'image/jpg'以使取回工作。

form.append(uploadFileName, {
  uri : localImage.full,
  type: 'image/jpeg',
  name: uploadFileName
 })

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

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

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

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("服务器正在运行!"))

如果你使用localhost,只需更改它:

来自:http://localhost: 3030 : http://10.0.2.2:3030

如果你在REST api中使用docker,我的一个工作案例是将主机名:http://demo.test/api替换为机器ip地址:http://x.x.x.x/api。你可以通过检查你的无线网络的ipv4来获取IP。你的手机也应该有wifi。