当我使用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模拟器没有连接到Wi-Fi。

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

其他回答

我在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>

通过在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上遇到了这个问题

URL - localhost / authToken。Json -没有工作:(

URL - 10.106.105.103 / authToken。Json -没有工作:(

URL- http://10.106.105.103/authToken.json -工作:):D

说明—在Linux操作系统中使用ifconfig,在Windows操作系统中使用ipconfig查找机器的IpAddress

这对我有用,android使用一个特殊类型的IP地址10.0.2.2然后端口号

import { Platform } from 'react-native';

export const baseUrl = Platform.OS === 'android' ?
    'http://10.0.2.2:3000/'
: 
'http://localhost:3000/';

对于Android,你可能错过了在AndroidManifest.xml中添加权限 需要添加以下权限。

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