Last updated: Mar 4, 2024
Reading timeยท3 min
Access the status
property on the response
object to get the status code
of an HTTP request made with the fetch
method.
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 of 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 an example that uses .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();
The status
property on the response
object will only be populated for HTTP
responses.
If the server doesn't respond at all, you encounter a CORS error or misspell the URL, you will get a network error.
The network error would run the catch()
function and the status
property
would not be populated as it isn't a server HTTP response.
fetch
Here is a complete example of 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();
We used 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, it's value will be false
.Fetch doesn't reject the promise response for HTTP requests on its own, so we
have to check if the ok
property was set to false
.
If the ok
property is set to false
, the request wasn't successful and we
have to throw an error on our own.
If there is a network error, e.g. a CORS error, or an error related to creating
the HTTP request, the promise would get rejected automatically and our catch
block would get triggered.
As previously noted, if there is a network error, the status
property will not
be populated as the error didn't come from a server HTTP response.
I've also written an article on how to get the status code of an Axios HTTP error.
You can learn more about the related topics by checking out the following tutorials: