在 Android 上 React Native Fetch 返回网络请求失败

IT技术 android reactjs http networking native
2021-05-14 06:12:17

我正在构建一个使用 Laravel 后端的 React Native 移动应用程序,目前在 localhost:8000 上运行。当从 Android 设备向我的服务器发出提取请求时,我的应用程序收到以下错误日志:

在此处输入图片说明

我的代码如下:

export default class App extends Component {
 login() {
    fetch('http://localhost:8000/api/establishments/get')
      .then((response) => response.json())
      .then((responseJson) => {
        console.log('success!');
      })
      .catch((error) => {
        console.error(error);
      });
  }

  render() {
    return (
      <TouchableOpacity activeOpacity={.5} onPress={() => this.login()}>
        <Text>Sign In</Text>
      </TouchableOpacity>
    );
  }
}

当我将确切的路由复制并粘贴到浏览器中时,服务器会按预期成功且完全地响应。我认为这是我的应用程序的网络权限问题?我一周前才刚刚开始学习 React Native,如果有任何帮助,我将不胜感激。

4个回答

iOS 在模拟器中运行,而 Android 在模拟器中运行。模拟器模拟真实设备,而模拟器只模拟设备。因此,Android 上的 localhost 指向模拟的 Android 设备,而不是运行服务器的机器。您应该使用机器的 IP 地址更改请求路径中的 localhost。

更多详情请访问:https : //github.com/facebook/react-native/issues/10404#issuecomment-267303151

我怀疑 127.0.0.1 或 localhost 将指向您当前运行服务器的计算机中的模拟器本身。如果您使用的是 AVD,请尝试将 127.0.0.1 / localhost 替换为 10.0.2.2;如果您使用的是 Genymotion 或使用计算机的实际 IP 地址,请尝试将其替换为 10.0.3.2。此外,您还应该确保您的 android 应用程序可以使用互联网。你可以通过添加来做到这一点

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

在您的 AndroidManifest.xml 中。

为 Laravel 和 React Native 建立解决方案(物理设备)

  1. 打开cmd运行ipconfig复制ipv4地址例如我的ipv4地址是192.168.43.235
  2. 为笔记本电脑和物理设备连接同一网络或打开热点并连接同一网络
  3. 现在运行命令启动 laravel 后端 php artisan serve --host=192.168.43.235 --port=8000
  4. 从react本机 api 服务更改 api url

apiService.js

    import axios from 'axios';
    
    const api_url = 'http://192.168.43.235:8000';
    
    export const getCategories = request =>
  axios
    .get(api_url + '/api/categories', {
      params: request || {},
    })
    .then(response => response.data);

主屏幕.js

import {getCategories} from '../services/ApiService';

async fetchCategories() {
    await getCategories()
      .then(response => {
        this.setState({
          dataCategories: response
        });
      })
      .catch(error => {
        console.log(error);
      });
  }
  1. 现在运行命令 start react native app react-native run-android

这就是全部...现在 api 请求工作正常。

更改 http://localhost:8000/api/establishments/get localhost with,你的模拟器一般可以达到 10.0.2.2 ;) 有 phun。