Tuesday, May 7, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  14] [ 2]  / answers: 1 / hits: 54727  / 6 Years ago, wed, august 22, 2018, 12:00:00

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


More From » node.js

 Answers
25

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')


[#53669] Monday, August 20, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johannatorim

Total Points: 599
Total Questions: 124
Total Answers: 100

Location: Virgin Islands (U.S.)
Member since Fri, May 7, 2021
3 Years ago
;