How to get data and response status from API using node-fetch?
Another alternative solution is using Promise.all
fetch('https://api.github.com/users/github')
.then(res => Promise.all([res.status, res.json()]))
.then(([status, jsonData]) => {
console.log(jsonData);
console.log(status);
});
Hope it helps
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')