How to get JavaScript fetch http response status?

To get https response status is always handy and easy. In JavaScript when we do the HTTP calls using fetch sometimes it might be difficult to get the response status. In our case, we were doing the following call and needed to check the success (200) status.

fetch("https://restcountries.eu/rest/v2/all",{
    method: 'GET', headers: {'Content-Type': 'application/json'},
})
    .then((response) => response.json())
    .then((apiResponse) => {
        // We needed the response status here 
        console.log(apiResponse)
    })
    .catch((error) => {
        console.error('Error:', error);
    });

The solution

fetch("https://restcountries.eu/rest/v2/all",{
    method: 'GET', headers: {'Content-Type': 'application/json'},
})
    .then((response) => response.json().then(res => ({status: response.status, data: res})))
    .then((apiResponse) => {
        console.log(apiResponse)
    })
    .catch((error) => {
        console.error('Error:', error);
    });
Share