Fetch always returns "Typeerror: Body has already been Consumed." How to fix?

Asked

Viewed 224 times

-2

I’m using the function fetch down below:

var url = "https://jsonplaceholder.typicode.com/users/2";

fetch(url).then(function(response) {
  if (!response.ok) {
    alert("Response not ok" + response.statusText);
    throw new Error(response.statusText);
  } else {
    alert(" Response Swal  Json:" + response.json());
  }

  return response.json();
}).catch(function(error) {
  alert("DeuErro -> " + error);

  swal.showValidationError(
    'Erro: ' + error
  )
})

But she always makes the mistake:

Typeerror: Body has already been Consumed.

What could be going on? What ways to correct?

  • Note: In the modal of the snippet you used to enter the code there is the "Organize" button. Use it to properly format the codes before creating the question to make it easier to read the codes.

  • Thanks for the @Woss tip, I didn’t know this button

  • 2

    Within the else, you already consume the body of the answer when you do response.json(); when you try to return the same value, there will no longer be content to be consumed. Why not assign this to a variable and reuse it in these two places?

1 answer

5


The method response.json will return a new promise, so you need to deal with it correctly. The easiest is to treat it with then chained:

var url = "https://jsonplaceholder.typicode.com/users/2";

fetch(url)
  .then(function(response) {
    if (!response.ok) {
      throw new Error(response.statusText);
    }

    return response.json();
  })
  .then(function (data) {
    console.log(data);
  })
  .catch(function(error) {
    console.error("DeuErro -> " + error);
  })

Thus the promise returned by response.json will be processed and the body of the response will be passed to the next then already treated as JSON.

An equivalent (and less chained) form would be using the async/await:

async function get_user_details(id) {
  const url = `https://jsonplaceholder.typicode.com/users/${id}`;
  const response = await fetch(url);
  
  return await response.json();
}

get_user_details(2).then(user => {
  console.log(user);
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.