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
php artisan serve --host 10.10.10.2 --port="8000"
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
And on your mobile app, make sure to use the correct URL in your request.
Make sure that CORS is enabled on 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!