简体   繁体   中英

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 => 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.

In your localhost:8000/api/coins localhost is pointing to the environment in which the code is running.

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. 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. (Eg: 192.168.1.22)

For iOS you have to set Domain Exception:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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