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

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 suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum 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.