Reread a response body from JavaScript's fetch

前端 未结 3 854
故里飘歌
故里飘歌 2021-01-03 22:53

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 respon

相关标签:
3条回答
  • 2021-01-03 23:17

    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.

    0 讨论(0)
  • 2021-01-03 23:22

    Assigning the response.json() to a variable and returning it worked for me. clone() was again saying its locked.

    fetch("http://localhost:3000/watchlist")
        .then(response => {
          var res = response.json();
          return res;
        })
        .then(data => {
          console.log(data);
          this.setState({ data });
        });
    
    0 讨论(0)
  • 2021-01-03 23:27

    I had to deal with an API that occasionally botched the JSON response - before returning response.json() I made a clone of the response object. using a catch block, I can determine if the error is a SyntaxError, and proceed to fix the error using the text result of the response clone

    a little like this:

    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 is just a function that fixes the received data - in my case, when it was broken JSON, it was always broken the same way - I think it had an extra leading { or trailing } - can't recall

    re-reading the question, you're more likely to want to log the error to the console rather than fix the 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
        });
    };
    
    0 讨论(0)
提交回复
热议问题