Borislav Hadzhiev
Sun Dec 26 2021·2 min read
Photo by Shelby White
To get the status code of an HTTP request made with the fetch
method, access
the status
property on the response
object. The response.status
property
contains the HTTP status code of the response, e.g. 200
for a successful
response or 500
for a server error.
async function makeRequest() { try { const response = await fetch('https://randomuser.me/api/'); console.log('response.status: ', response.status); // 👉️ 200 console.log(response); } catch (err) { console.log(err); } } makeRequest();
We awaited the response from calling the
fetch method and
assigned the result to a response
variable.
To get the status code of the HTTP response, access the
status
property on the response
object.
Here is the same example, but using .then()
and .catch()
instead of
async/await
.
function makeRequest() { fetch('https://randomuser.me/api/') .then(response => { console.log('response.status: ', response.status); // 👉️ 200 console.log(response); }) .catch(err => { console.log(err); }); } makeRequest();
Note that the status
property on the response
object will only be populated
for HTTP responses.
catch
function and thestatus
property would not be populated as it isn't a server HTTP response.Here is a complete example of how you would go about handling requests and
errors using fetch
.
async function makeRequest() { try { const response = await fetch('https://randomuser.me/api/'); console.log('status code: ', response.status); // 👉️ 200 if (!response.ok) { console.log(response); throw new Error(`Error! status: ${response.status}`); } const result = await response.json(); return result; } catch (err) { console.log(err); } } makeRequest();
Notice that we use the
response.ok
property to check if the server responded with a status in the range of
200-299
.
response.ok
property will have a value of true
, otherwise false
.Because fetch doesn't reject the promise response for HTTP requests on its own,
we have to check if the ok
property was set to false
- meaning the request
was not successful and throw an error on our own.
catch
block would get triggered.As noted previously, if there is a network error, the status
property will not
be populated as the error did not come from an HTTP response from the server.