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

当前回答

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

其他回答

只需添加

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

    <application
      android:usesCleartextTraffic="true"

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

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

Android用户:

Replace localhosts to a Lan IP addresses because when you run the project on an Android device, localhost is pointing to the Android device, instead of your computer, example: change http://localost to http://192.168.1.123 If your request URL is HTTPS and your Android device is under a proxy, assume you have installed User-added CA(like burp suite's CA or Charles's CA) in your Android device, make sure your Android version is below Nougat(7.0), because: Changes to Trusted Certificate Authorities in Android Nougat User-added CAs Protection of all application data is a key goal of the Android application sandbox. Android Nougat changes how applications interact with user- and admin-supplied CAs. By default, apps that target API level 24 will—by design—not honor such CAs unless the app explicitly opts in. This safe-by-default setting reduces application attack surface and encourages consistent handling of network and file-based application data.

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

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

通过在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,看

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