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.
JAVASCRIPT
const response = awaitfetch("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:
JAVASCRIPT
const response = awaitfetch("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:
JAVASCRIPT
try {
const response = awaitfetch("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!
To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!