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

当前回答

“依赖”:{“反应”:“17.0.2”、“react-native”:“0.66.1”}, 我在使用Android模拟器时遇到了这个问题。

将这些代码行添加到AndroidManifest.xml中 <应用程序 .... .... android: usesCleartextTraffic = " true " > 然后,试着在一个真正的物理设备上运行你的代码,而不是模拟器, 要在物理设备上运行,请连接usb并尝试运行NPX react-native run-android

其他回答

解决方案很简单,更新nodejs版本14或更高

只是你有Fetch....的变化

fetch('http://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
        /*return responseJson.movies; */
        alert("result:"+JSON.stringify(responseJson))
        this.setState({
            dataSource:this.state.dataSource.cloneWithRows(responseJson)
        })
     }).catch((error) => {
         console.error(error);
     });

只需添加

<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使用一个特殊类型的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/';

React Native Docs给出了这个问题的答案。

苹果已经阻止隐式明文HTTP资源加载。所以我们需要添加以下我们的项目的信息。Plist(或等效)文件。

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

测试您的集成->添加应用程序传输安全例外