Home > Software engineering >  How can I retrieve the body of a 300 Multiple Choice status?
How can I retrieve the body of a 300 Multiple Choice status?

Time:12-14

I am making a GET request to an API that returns JSON. The response is usually JSON with a status 200. However, in rare cases it returns a status 300 with JSON. That 300 response gets caught in my React app as a ResponseError.

I am able to see the contents of the body in the network tab, and console.log(e.response.body) shows that it's a ReadableStream, but e.response.body.json() throws a TypeError.

The 200 status returns an object like:

{
  user: { ... }
}

The 300 status returns an object like the following that can only be seen in the network tab:

{
  users: {
    user1: { ... },
    user2: { ... }
}

How can I access the contents of the response body in my React app? The GET is made with fetch. Here's a simple example of what's happening:

  try {
    const res = await fetch('/api/user')
    const data = await res.json()
    // status 200 always works
  } catch(e) {
    // 300 status always goes here 
    // e.response.body is a ReadableStream 
    const await res = e.response.body.json() // throws a TypeError 
  }

In the catch block, I tried e.response.body.json(). That throws a TypeError.

CodePudding user response:

Here is the documentation https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

 fetch('/api/user')
      .then((response) => response.json())
      .then((data) => console.log(data))
      .catch((error) => {
        console.error('Error:', error);
      });

CodePudding user response:

You can avoid try catch block and use fetch API only as

  fetch('/api/user')
        .then((response) => {
           if(response.status == 300 || response.status == 200){
             return res.json()
           }
        })
        .then((data) => console.log(data))
        .catch((error) => {
           console.error('Error:', error);
         });
  • Related