Home > Software engineering >  React | Can not fetching data from local api
React | Can not fetching data from local api

Time:08-17

I have a React app on 127.0.0.1:3000 / 192.168.0.104:3000 and a Laravel api on 127.0.0.1:8000.

My problem is, I can fetch the data on my computer (127.0.0.1), but it seems that the React app can't correctly get the data from the database when I access the React app from my phone on LAN (192.168.0.103).(I can see the React app)

Can someone help me to solve this problem or tell me what may cause this? Thank you.

CodePudding user response:

I suspect you have a CORS policy error. I'm not familiar with Laravel cause you know, PHP, but a quick google search would probably tell you how to allow a foreign domain to have access to your api.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

To verify you have a cors policy error, you'd have to open dev tools and take a look at the errors. However, I'm unsure if that's possible on a mobile browser. I never tried, so it could be possible. Again another google search would answer that for you.

CodePudding user response:

Sorry about that. I just solved this problem by myself. It is because that the client can not find the Laravel API on LAN. In Img A the port 8000 is not open on the machine, so the client can't access the API.

Img A

My solution is that host the API and APP on the different machine and make sure that the client can access both the APP and API.

Img B

  • Related