Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reread a response body from JavaScript's fetch

fetch() returns promise which (if successful) resolves to a Response object. A very common thing to do is immediately call Response.json() to convert the response body to a JSON object.

If the response body isn't valid JSON, then the Response.json() promise fails with an error. The message is something along the lines of:

Unexpected token X in JSON at position 0

That's not very helpful when trying to diagnose the problem; ideally I'd like to be able to see the content from the server (which is often an error message).

However, it appears that you can only read the stream at Response.body once (at least in Chrome). (There's even a read-only Response.bodyUsed flag.) That has already happened when Response.json() tries to convert the body to JSON, so the body appears to be lost forever in the event of a JSON parsing failure.

Is there any way to recover the original response body... short of manually reading it (and then converting to JSON) when the original fetch Promise resolves?

like image 206
Craig Walker Avatar asked Nov 08 '16 22:11

Craig Walker


People also ask

Which method call is changed to handle a successful response returned by Fetch?

This is the first method called in our fetch() chain, if it resolves, we then call our json() method which again returns a Promise from the response. json() call. After this we have an object of the parsed JSON. If the parsing fails the Promise is rejected and the catch statement executes.

What is response JSON () in fetch?

json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .

How do I respond to a fetch API in HTML?

To get a response as an HTML string, you can use the text() method. Here is an example that downloads the Google homepage as an HTML string and prints it on the console: fetch('https://www.google.com') . then(res => res.


1 Answers

Use Response.clone() to clone Response

let clone = response.clone(); 

Alternatively, use Response.body.getReader() which returns a ReadableStream to read Response as a stream, TextDecoder() to convert Uint8Array data stream to text.

like image 123
guest271314 Avatar answered Sep 21 '22 06:09

guest271314