Network Request Failed/Network Error in React Native using Laravel API and Android emulator

kevilondo

Kevin Ilondo

Posted on December 11, 2020

Network Request Failed/Network Error in React Native using Laravel API and Android emulator

If you are currently working on an app with React Native and you are using Laravel as your backend, you have probably encountered this problem.
And this article will help you solve this problem with just ONE SIMPLE TRICK.

SOMETIMES THIS PROBLEM IS CAUSED BY HOW YOU START YOUR LARAVEL APP

We all know how to start a Laravel server with the simple php artisan serve command and that’s the problem.
By starting your Laravel app like that it creates a link for your app which is localhost:8000 (the port may be different for you, it might be 3000, 8080 or anything else but we will use 8000 for this tutorial).
When making an HTTP Request with React Native, there is some kind of conflict because your Android app is run on an emulator which uses localhost too, and instead of sending the request to the localhost on your computer, it sends the request to the phone itself but with a different port and that is why you are getting this error.

THE TRICK THAT HELPED ME

Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

D:\xampp\htdocs\projects\laravel\blog>php artisan serve --host 10.10.10.2 --port="8000"
Laravel development server started: http://10.10.10.2:8000
Enter fullscreen mode Exit fullscreen mode

Just start the server by giving an IP address and a port
It’s just that simple! Start your app as usual but don’t forget to give an IP address and a port, this will help you solve the Network Request Failed error.

NOTE: Replace 10.10.10.2 with your own IP Address, this is just an example.

//with axios
await axios.post('http://10.10.10.2:8000/api/user/login', data, headers)
    .then(res => {
      console.log(res.data)
    })
//with Fetch
await fetch('http://10.10.10.2:8000/api/user/login', {
method: "POST",
headers: headers //put your headers,
body: body //put the body here
})

Enter fullscreen mode Exit fullscreen mode

And on your mobile app, make sure to use the correct URL in your request.
Make sure that CORS is enabled in your backend to avoid errors related to CORS. Next time I will make make a detailed post about how to enable it and how to solve issues related to CORS.

CONCLUSION

Start your Laravel app and enter your IP address and a port
Use the URL in your HTTP Request.
That’s it, I hope this post was useful to you and happy coding!

💖 💪 🙅 🚩
kevilondo
Kevin Ilondo

Posted on December 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related