Android上的React Native Fetch返回网络请求失败 [英] React Native Fetch on Android returns Network request failed

查看:85
本文介绍了Android上的React Native Fetch返回网络请求失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am building a React Native mobile application that is using a Laravel backend, currently running on localhost:8000. When making a fetch request from an Android device to my server, my application gets the following error logs:

我的代码如下:

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,非常感谢您提供任何帮助.

When I copy and paste the exact route into my browser, the server responds successfully and completely as expected. I believe it is an issue with network permissions from my application? I have only just began learning React Native a week ago and would appreciate any help at all.

推荐答案

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

iOS runs in a simulator while Android runs in an emulator. Emulator emulates a real device, while simulator only imitates a device. Therefore localhost on Android points to the emulated Android device instead of the machine where your server runs. You should change localhost in yours request paths with the IP address of your machine.

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

More details at: https://github.com/facebook/react-native/issues/10404#issuecomment-267303151

这篇关于Android上的React Native Fetch返回网络请求失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆