How to Get the Status Code of a Fetch HTTP Response in JavaScript
Table of Contents
When you make a request on the web, the status code is what lets you know the status of the response.
This is useful because when you know the request failed, you can handle the error accordingly, or proceed with the data if the request was successful.
In this post, we will look at how to get the status code of a response when using the Fetch API in JavaScript.
How to get the status code of a response
To get the status code of a response, first let's make a request:
JAVASCRIPTconst response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
Then, we can get the status code of the response by accessing the status
property:
JAVASCRIPTconst response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const statusCode = response.status;
If the request was successful, the status code will be 200
.
Alternatively, you can check for response.ok
which will return a boolean for you if the status code is between 200
and 299
.
JAVASCRIPTconst response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const isSuccessful = response.ok;
if (isSuccessful) {
// do something
}
Once successful, you can get the JSON, text, or blob data from the response:
JAVASCRIPTconst response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const isSuccessful = response.ok;
if (isSuccessful) {
const data = await response.json();
// do something with the data
}
To play it safe, you could wrap all your code inside a try/catch
block:
JAVASCRIPTtry {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const isSuccessful = response.ok;
if (isSuccessful) {
const data = await response.json();
// do something with the data
}
} catch (error) {
// handle the error
}
Conclusion
In this post, we looked at how to get the status code of a response when using the Fetch API in JavaScript.
Simply call the status
property on the response object to get the status code.
Thanks for reading!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Managing PHP Dependencies with Composer
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js