简体   繁体   English

React Native Fetch 不能在本地使用 laravel API

[英]React Native Fetch not working with laravel API Locally

I am trying to fetch laravel API locally in react-native.When I try with remote url it works but it's not working with local server.I am using android studio emulator and我正在尝试在 react-native 中本地获取 laravel API。当我尝试使用远程 url 时,它可以工作,但不能与本地服务器一起使用。我正在使用 android studio 模拟器和

react-native => 0.59.8, 
laravel => 5.7

My Code我的代码

 async submit() {

    //https://facebook.github.io/react-native/movies.json => this works

    try {
        let response = await fetch('localhost:8000/api/coins');
        let responseJsonData = await response.json();
        console.log(responseJsonData, 'data');
    } catch (e) {
        console.log(e, 'error')
    }
};

Error错误

05-20 14:46:08.167  4749  8885 I ReactNativeJS: { [TypeError: Network request failed]
05-20 14:46:08.167  4749  8885 I ReactNativeJS:   line: 24115,
05-20 14:46:08.167  4749  8885 I ReactNativeJS:   column: 31,
05-20 14:46:08.167  4749  8885 I ReactNativeJS:   sourceURL: 'http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false' }, 'error'

This Might be an issue这可能是一个问题

iOS is running in a simulator and Android is running in an emulator. iOS 在模拟器中运行,而 Android 在模拟器中运行。

In your localhost:8000/api/coins localhost is pointing to the environment in which the code is running.在您的localhost:8000/api/coins localhost指向代码运行的环境。

The emulator emulates a real device while the simulator is only imitating the device.模拟器模拟真实设备,而模拟器只是模仿设备。 So localhost on Android is pointing to the emulated Android device.因此,Android 上的localhost指向模拟的 Android 设备。 And not to the machine on which your server is running.而不是运行服务器的机器。

Solution解决方案
The solution is to replace localhost with the IP address of your machine.解决方案是将localhost替换为您机器的 IP 地址。 (Eg: 192.168.1.22) (例如:192.168.1.22)

For iOS you have to set Domain Exception:对于 iOS,您必须设置域例外:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <false/>
  <key>NSExceptionDomains</key>
  <dict>
    <key>cocoacasts.com</key>
    <dict>
      <key>NSIncludesSubdomains</key>
      <true/>
      <key>NSExceptionAllowsInsecureHTTPLoads</key>
      <true/>
    </dict>
  </dict>
</dict>

or allow all Domain:或允许所有域:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
      <true/>
</dict>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM