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

Android上的React Native Fetch返回网络请求失败,android,reactjs,http,networking,native,Android,Reactjs,Http,Networking,Native,我正在构建一个React本地移动应用程序,该应用程序使用Laravel后端,目前运行在localhost:8000上。从Android设备向我的服务器发出获取请求时,我的应用程序会收到以下错误日志: 我的代码如下: export default class App extends Component { login() { fetch('http://localhost:8000/api/establishments/get') .then((response) =>

我正在构建一个React本地移动应用程序,该应用程序使用Laravel后端,目前运行在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,非常感谢您的帮助。

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


在AndroidManifest.xml中。

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

更多详细信息请访问:

使用更改本地主机,您的仿真器一般可以达到10.0.2.2;让phun.

为Laravel和react天然物理设备创建解决方案

打开cmd运行ipconfig复制ipv4地址例如,我的ipv4地址是192.168.43.235 为笔记本电脑和物理设备连接相同的网络,或打开热点并连接相同的网络 现在运行命令start laravel backend php artisan serve-host=192.168.43.235-port=8000 从本机api服务更改api url apiServise.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);
homescreen.js

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

async fetchCategories() {
    await getCategories()
      .then(response => {
        this.setState({
          dataCategories: response
        });
      })
      .catch(error => {
        console.log(error);
      });
  }
现在运行命令start react native app react native run android
这就是全部…现在api请求工作正常。

我还尝试将axios添加到我的React本机应用程序中,并使用axios.get。。。我得到的错误日志与使用fetch时相同,如上图所示。很抱歉,我没有指定。我正在从我的终端使用“npm start”命令,并部署到我的物理设备Galaxy S8+。你能通过手机访问互联网吗?你和你的电脑在同一个网络中吗?是的,我和我的笔记本电脑在同一个WiFi上,在我的手机上。你在android清单上有这个吗:启用互联网?你知道AndroidManifest.xml在哪里吗?