Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data and response status from API using node-fetch?

As per the node-fetch documentation node-fetch

we can get the response status like this

fetch('https://github.com/')
    .then(res => {
        console.log(res.status);
    });

and for getting the data

fetch('https://api.github.com/users/github')
    .then(res => res.json())
    .then(jsonData => console.log(jsonData));

I have a scenario where I need to return the JSON data and the status from the response. I tried to use like this

     fetch('https://api.github.com/users/github')
            .then(res => res.json())
            .then(jsonData => {
             console.log(jsonData);
             console.log(jsonData.status);
      });

but the

console.log(jsonData.status)

won't return the status. How I can get status and output data

like image 250
Dony Joseph Avatar asked Aug 22 '18 19:08

Dony Joseph


People also ask

How can I get response data from fetch call?

The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

Does fetch API work in node?

Fetch is already available as an experimental feature in Node v17. If you're interested in trying it out before the main release, you'll need to first download and upgrade your Node. js version to 17.5.

How do I get API data in node JS?

The simplest way to call an API from NodeJS server is using the Axios library. Project Setup: Create a NodeJS project and initialize it using the following command. Module Installation: Install the required modules i.e. ExpressJS and Axios using the following command.


1 Answers

The easiest solution would be to declare a variable and assign res.status value to it:

let status; 
fetch('https://api.github.com/users/github')
  .then((res) => { 
    status = res.status; 
    return res.json() 
  })
  .then((jsonResponse) => {
    console.log(jsonResponse);
    console.log(status);
  })
  .catch((err) => {
    // handle error
    console.error(err);
  });

You can also try it that way using async/await:

const retrieveResponseStatus = async (url) => {
  try {
    const response = await fetch(url);
    const { status } = response; 
    return status;
  } catch (err) {
   // handle error
    console.error(err);
  }
}

Then You can use it with any URL You want:

const status = await retrieveStatus('https://api.github.com/users/github')

like image 165
KarlR Avatar answered Oct 16 '22 14:10

KarlR