1

I can fetch data easily in a React app.But when I am going to fetch data in a React-Native app. It shows [AxiosError: Network Error] error.

axios
      .get(`http://localhost:8000/api/products`)
      .then(res => setProducts(res?.data))
      .catch(error => console.log(error));
  }, []);
1
  • Use ngrok for simulating you localhost as a valid server for others and then try. For sure it will. Commented Sep 5, 2022 at 12:08

2 Answers 2

0

I assume you are trying to make the calls from an emulator?

If yes, localhost is not going to work. Depending on whether you are running ios or android you have to call

10.0.2.2 for Android or 127.0.0.1 for ios. (I know 127.0.0.1 should be the same as localhost, but it seems that is not the case in the ios emulator. Would be interesting to know why exactly that is the case)

A little more infos here

Sign up to request clarification or add additional context in comments.

2 Comments

Still not working.I am trying to make calls from an android phone
Then that is the reson. When you want to access localhostfrom your phone, the phone assumes you have a server running on the phone. What you need is some kind of config to bridge the network of your device with the network of your computer in order for this to work. Maybe this helps.
0

Hey you just cant connect directly localhost with your react-native develpoment since it already has a port assigned on which it runs.

You can check this article which explains greatly about how to cinfugyre. React Native Android Fetch failing on connection to local API

Basically you have to map your port to via ADB

this is the exact quote:

You are not able to access your local development server because that port hasn't been forwarded by ADB yet. When you run react-native run-android, React Native maps the port 8081 with your mobile device on USB. When you disconnect your USB you won't be able to refresh or hot reload your code anymore. So in this situation you can do 2 things, either map your local server port just like React Native does or use your local IP address

Do lemme know in case of any concerns

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.