Razi Melliti
Razi Melliti

Reputation: 210

fetching data from laravel API to react native app ( created with expo )

i created a react native app using expo and i'm running it on an android device with the expo app or USB cable , in addition to a laravel APi that i'm using it to test if anything is OK before implementing authentication , the thing is that i'm always getting the error message ( i defined it in the fetch function ) , i said maybe it's because of the URL but when i try it on the web it work fine ! i hope that this explanation is clear ! i need help to get the data from the laravel api to the react native app !

react native :

the constructor code :

 constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: "",
    };
  }

this is the fetch function :

_onLoginPressed = () => {
    fetch("http://127.0.0.1:8000/api/indexp", {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },

    })
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson);

          Alert.alert("logged");

      })
      .catch((error) => {
        console.log('erroc message');
      });
  };

the expo is runnig in this adress (LAN): exp://192.168.1.4:19000

laravel :

in api.php

Route::get('indexp','PostsController@indexp');

in PostsController :

  public function indexp()
    {
        $post = Post::all();

        return response()->json($post);
    }

enter image description here

if i install android studio and run it on an emulator maybe it will work ?

Upvotes: 0

Views: 3067

Answers (2)

Gene Artista
Gene Artista

Reputation: 51

Like "julix" said, the problem is in the URL, expo or react native apps does not recognize http request localhost instead use your ip address, with laravel set manually the server's host from the default 127.0.0.1 to 192.168.0.1(YOUR IP ADDRESS) with a port of 8000

Upvotes: 0

julix
julix

Reputation: 76

Your problem is at the fetch request. You need to access the IP of the API server, in this case the LAN address of your PC (run ifconfig on linux or ipconfig in windows). Then you have to start your webserver with that IP as host, and set a port if you want, i.e. php artisan serve --host 192.168.10.100 --port 8000, where the IP is the IP of your PC and the port is the one you like.

Then on your fetch request you have to go the http://192.168.10.100:8000/api/indexp and get the results from there. I would recommend not getting the IP and port on each file, but putting them on a config file so if you need to change them you just change in one place

Upvotes: 2

Related Questions