javascriptfetch-api

Returning HTML With fetch()


I'm trying to fetch a file and return its HTML. However it's not as simple as I'd have imagined.

    fetch('/path/to/file')
    .then(function (response) {
      return response.body;
    })
    .then(function (body) {
      console.log(body);
    });

This returns an object called ReadableByteStream. How do I use this to grab the HTML file content?

If I change the contents of /path/to/file to be a JSON string, and change the above to:

    fetch('/path/to/file')
    .then(function (response) {
      return response.json();
    })
    .then(function (json) {
      console.log(json);
    });

... it returns the JSON correctly. How do I do fetch HTML?


Solution

  • You need to use the .text() method, instead of .json(). This converts the byte stream into plain text, which can be parsed by the browser as HTML.