React Native Fetch 无法在本地使用 laravel API

React Native Fetch not working with laravel API Locally

我正在尝试在 react-native.When 中本地获取 laravel API 我尝试使用远程 url 它有效,但它不适用于本地 server.I 我正在使用 android 工作室模拟器和

react-native => 0.59.8, 
laravel => 5.7

我的代码

 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')
    }
};

错误

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'

对于 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>

或允许所有域:

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

这可能是个问题

iOS 在模拟器中是 运行,Android 在模拟器中是 运行。

在您的 localhost:8000/api/coins 中,localhost 指向代码所在的环境 运行。

模拟器模拟的是真实设备,而模拟器只是模仿设备。 所以 Android 上的 localhost 指向模拟的 Android 设备。而不是您的服务器 运行.

所在的机器

解决方案
解决办法是用你机器的IP地址替换localhost。 (例如:192.168.1.22)