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!
How to Install Node on Windows, macOS and Linux
Getting Started with Solid
Getting Started with Svelte
Getting Started with Electron
Git Tutorial: Learn how to use Version Control
How to Set Up Cron Jobs in Linux
Best Visual Studio Code Extensions for 2022
How to build a Discord bot using TypeScript
How to deploy a Node app using Docker
Using Puppeteer and Jest for End-to-End Testing
How to Scrape the Web using Node.js and Puppeteer
Creating a Twitter bot with Node.js
