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
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.
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With