Reread response body from JavaScript request

fetch()returns a promise that (if successful) resolves the object Response. Very often, you need to call Response.json()to convert the response body to a JSON object.

If the response body is not valid JSON, then the promise Response.json()fails. The message is something like:

Unexpected X token in JSON at position 0

This is not very useful when trying to diagnose a problem; Ideally, I would like to see content from the server (which is often an error message).

However, it looks like you can only read the stream Response.bodyonce (at least in Chrome). (There’s even a flag there Response.bodyUsed. This already happened when Response.json()trying to convert the body to JSON, so the body seems to be lost forever if the JSON parsing fails.

Is there a way to restore the original body of the response ... except for manually reading it (and then converting to JSON) when the fetchPromise repository allows?

+4
source share
2 answers

Use Response.clone()for cloningResponse

let clone = response.clone();

Response.body.getReader(), ReadableStream Response , TextDecoder() Uint8Array .

+7

API, JSON - response.json() . catch, , SyntaxError, ,

:

var brokenJson = function (url) {
    var responseCopy;
    return fetch(url)
    .then(function (response) {
        responseCopy = response.clone();
        return response.json();
    }).catch(function (err) {
        if (err instanceof SyntaxError) {
            return responseCopy.text()
            .then(function(data) {
                return fixJson(data);
            });
        }
        else {
            throw err;
        }
    }).then(function (json) {
        // do things
    });
};

fixJson - , - , JSON, - , ( ) -

, , , , json-easy rewrite:

var brokenJson = function (url) {
    var responseCopy;
    return fetch(url)
    .then(function (response) {
        responseCopy = response.clone();
        return response.json();
    }).catch(function (err) {
        if (err instanceof SyntaxError) {
            return responseCopy.text()
            .then(function(text) {
                console.error(text);
                throw err;
            });
        }
        else {
            throw err;
        }
    }).then(function (json) {
        // do things
    });
};
+2

Source: https://habr.com/ru/post/1660239/


All Articles