Search code examples
javascriptjsonfetch-apihttpresponse

Failed to execute 'json' on 'Response': body stream already read


I am getting an error when I try to read a response twice: I need the response in a form of text assigned to a cosnt, e.g. (api_response.text()) and then I need to pass the api_response.json() to a function:

if (api_response_text == 'true') {
  const api_request = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(item),
  }).then(async api_response => {
    const api_response_text = await api_response.text();
    if (api_response.ok) {
      if (onCompleted) {
        onCompleted(await api_response.json());
      }    
    } else {                
      console.log(api_response_text)
    }
  });
}

I tired with clone() like so:

const api_response_clone = await api_response.clone();

and:

console.log(api_response_clone.text());

but then I got [object Promise] as the response text, which is not what I need.

Any suggestions how to fix this?


Solution

  • Move the call to text() to the else block, since that's the only place where you need the raw text.

    Mixing await and .then() also makes your code more confusing than necessary. Stick to await when you can.

    if (api_response_text == 'true') {
      const api_response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(item),
      });
      if (api_response.ok) {
        if (onCompleted) {
          onCompleted(await api_response.json());
        }
      } else {
        console.log(await api_response.text());
      }
    }