huytrongnguyen / rosie

MIT License
0 stars 0 forks source link

TypeError: Failed to execute 'text' on 'Response': body stream already read #1

Closed huytrongnguyen closed 10 months ago

huytrongnguyen commented 10 months ago

Current behavior

TypeError: Failed to execute 'text' on 'Response': body stream already read

// rosie/ts/src/core/ajax.ts
try {
  return await res.json();
} catch {
  return await res.text() as T;
}

Expected behavior

The request completes without throwing an error

Solution

https://stackoverflow.com/questions/53511974/javascript-fetch-failed-to-execute-json-on-response-body-stream-is-locked

// This works fine because the data is being consumed only once.
const response = await fetch(url, request);
const data = await response.text();
try {
  return JSON.parse(data);
} catch (error) {
  console.warn(`API response is not JSON. Falling back to plain text.`, error);
  return data;
}