3

I'm facing an issue in React fetch, it gives me an incomplete response, so when I parse the response into JSON, it was returning me an error.

Code:

export default async (url, body = null, method = 'GET') => {
  let config = {
      method,
  };
  try {
      const response = await fetch(url, config);
      if (!response.ok) {
          throw new Error(response.statusText);
      }
      return await response.json();
  } catch (error) {
      console.warn(error);
      throw error;
  }
};

Response log: Response log

Does fetch has a maximum response size? If yes, how to increase it?

Justinus Hermawan
  • 1,194
  • 1
  • 23
  • 44

1 Answers1

4

There's no max limit to fetch response size.

The error in your case means that you are reading the response body more than once. Try guarding the .json() calls with Body.bodyUsed.

See https://developer.mozilla.org/en-US/docs/Web/API/Body

nilobarp
  • 3,806
  • 2
  • 29
  • 37
  • It's an async function so it will called more than once, isn't it? You mean, I need to validate whether `bodyUsed` was true or not on `.json()` call? – Justinus Hermawan Oct 20 '17 at 02:40
  • @JustinusHermawan See [Reread a response body from JavaScript's fetch](https://stackoverflow.com/questions/40497859/reread-a-response-body-from-javascripts-fetch/), [How do download of Json using Fetch in JavaScript?](https://stackoverflow.com/questions/46797810/how-do-download-of-json-using-fetch-in-javascript/) – guest271314 Oct 20 '17 at 02:47
  • @guest271314 I don't have any problem with `TypeErrror: already read`, it just because I'm debugging with `response.text()`, just ignore it. My problem was in the truncated JSON response as I saw in `response.text()` log. – Justinus Hermawan Oct 20 '17 at 02:55
  • @JustinusHermawan `Response.body` can only be read once. `.json()` call reads the `ReadableStream` that is `Response.body`, see also [Why fetch Body object can be read only once?](https://stackoverflow.com/questions/46742251/why-fetch-body-object-can-be-read-only-once/) – guest271314 Oct 20 '17 at 02:55
  • @JustinusHermawan _"My problem was in the truncated JSON response as I saw in `response.text()` log. "_ Did you expand the JavaScript object at the `console`? – guest271314 Oct 20 '17 at 02:56
  • @guest271314 Yes I did. It seems larger size while in Chrome dev tools. Sometimes it's completely (https://imgur.com/a/PpKse) but sometimes it's missing the last `}` bracket (https://imgur.com/a/4laG9). – Justinus Hermawan Oct 20 '17 at 03:11
  • Try `console.log(JSON.stringify(), null, 2)` – guest271314 Oct 20 '17 at 03:13
  • There would probably be a parse error if the response was invalid `JSON` when passed to `JSON.stringify()`. Not certain what issue is? – guest271314 Oct 20 '17 at 03:19
  • @guest271314 But it always return completely when requesting from browser or postman. – Justinus Hermawan Oct 20 '17 at 03:19
  • @guest271314 Yes, it was error when I call `.json()`. – Justinus Hermawan Oct 20 '17 at 03:20