Categories
JavaScript Answers

How to get the response JSON and response status with JavaScript fetch?

Spread the love

Sometimes, we want to get the response JSON and response status with JavaScript fetch.

In this article, we’ll look at how to get the response JSON and response status with JavaScript fetch.

How to get the response JSON and response status with JavaScript fetch?

To get the response JSON and response status with JavaScript fetch, we can get the status property from the response object.

For instance, we write:

(async () => {
  const r = await fetch("https://jsonplaceholder.typicode.com/posts/1")
  const body = await r.json()
  const {
    status
  } = r
  const obj = {
    status,
    body
  }
  console.log(obj)
})()

We make a GET request with fetch.

Then we call r.json to get the response body JSON.

Next, we get the status property from the r response object.

And then we combine them into one object and assign it to obj.

Therefore, obj is:

{
  "status": 200,
  "body": {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  }
}

Conclusion

To get the response JSON and response status with JavaScript fetch, we can get the status property from the response object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *