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
- Getting Started with Express
- Create an RSS Reader in Node
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API