React Native json-server, AXIOS and Error Code 500

RR
2 min read

Table of contents

In this blog, I'll document my experience as a beginner in fetching data. I will try to show how to get data and also solutions for the problems you may encounter while trying to get data from APIs and your localhost. First let's look at using json-server, which is a fake REST API tool, where we can use our own server in localhost. By using instructions from their GitHub:

Install json-server:

npm install -g json-server

Create db.json on your main path of your project(where eslint, prettier, package.json is.):

  "user": [
    {
      "email": "1",
      "password": "1",
      "username": "1",
      "id": 1
    }
  ]
}

Start JSON Server

json-server --watch db.json

Now at http://localhost:3000/user/1, you have your user info. They have more detailed explanations and a link to a video on their GitHub.

Let's say you want to fetch the user data from your local server. With Axios:

const fetchDataAxios = () => {
  axios.get('http://localhost:3000/user')
}

Or you want to post something on your local server:

let result = await axios.post(          
    "http://localhost:3000/user",        
    {                                    
      "color":  "blue",
      "tone": "light",
    }
  );

But here you may run into some problems. For example:

  • Promise Rejection,

the reason may be this:

The thing is, iOS is running in a simulator and Android is running in an emulator. The localhost is pointing to the environment in which the code is running. The emulator emulates a real device while the simulator is only imitating the device. Therefore the localhost on Android is pointing to the emulated Android device. And not to the machine on which your server is running. The solution is to replace localhost with the IP address of your machine. (source: https://github.com/facebook/react-native/issues/10404#issuecomment-267303151)

this problem may be solved by:

opening cmd and typing:

ipconfig

and paste your ip given in the IPv4 section instead of localhost. i.e.: http://localhost:3000/user -> http://xxx.xx.x.xx:3000/user

or you can try: using http://10.0.2.2:3000/user to access your actual machine. More info here: https://stackoverflow.com/questions/5528850/how-do-you-connect-localhost-in-the-android-emulator

  • AxiosError: Request failed with status code 500,
// to understand the error message clearly

try {
  let result = await axios.post(     
    "http://localhost:3000/user",         
    {                                    
      some: "data",
    }
  );
  console.log(result.response.data);
} catch (error) {
  console.error(error.response.data);     // NOTE - use "error.response.data` (not "error")
}
//source: https://stackoverflow.com/a/66234804

or here a lot of other solutions: stackoverflow

0
Subscribe to my newsletter

Read articles from R directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

R
R