Returning HTML With fetch()

JavascriptFetch Api

Javascript Problem Overview


I'm trying to fetch a file and return it's 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?

Javascript Solutions


Solution 1 - Javascript

You can download the html with fetch and then parse it with DomParser API.

fetch('somePage.html')
    .then(function(response) {
        // When the page is loaded convert it to text
        return response.text()
    })
    .then(function(html) {
        // Initialize the DOM parser
        var parser = new DOMParser();

        // Parse the text
        var doc = parser.parseFromString(html, "text/html");

        // You can now even select part of that html as you would in the regular DOM 
        // Example:
        // var docArticle = doc.querySelector('article').innerHTML;

        console.log(doc);
    })
    .catch(function(err) {  
        console.log('Failed to fetch page: ', err);  
    });

Solution 2 - Javascript

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.

Solution 3 - Javascript

you can return the response with .text(), and then render the page in the doc as you want.

function fetchHtml() {
  fetch('./file.html')
  .then((response) => {
    return response.text();
  })
  .then((html) => {
    document.body.innerHTML = html     
  });
}

Solution 4 - Javascript

Using Promise Chaining with .then() is an older way of coding fetches and responses. A more modern way would be to use async functions and await like the following:

async function fetchMyDocument() {      
  try {
    let response = await fetch('/path/to/file.html'); // Gets a promise
    document.body.innerHTML = await response.text(); // Replaces body with response
  } catch (err) {
    console.log('Fetch error:' + err); // Error handling
  }
}

And about the direct answer to the question, (like every other answer) .text() is used instead of .json() on the response.

Solution 5 - Javascript

It should be:

fetch('/path/to/file').then(function(response) {
    return response.text();
}).then(function(string) {
    console.log(string);
}).catch(function(err) {  
    console.log('Fetch Error', err);  
});

Solution 6 - Javascript

  • 1- call function fetch and add the path of the page.

  • 2- then convert the fetch data to text by function .text().

  • 3- then append the page component to your parent container.

       async function getAbout() {


    await fetch('./component/about.html').then(res => res.text()).then(data => {
    page_2.innerHTML = data;

     }).then(() => {
       
         // after fetch write js code here  
     })}

  • for fetch, component don't add <body> or <HTML> tag < just use other like <div> or other tags.

  • for better performance use async-await!.

Solution 7 - Javascript

Use this:

var fetchAndParse = async (url) => { let div = document.createElement("div"); div.innerHTML = await (await fetch(url)).text(); return div }

Today I wanted to know the length of all the OpenSource licenses. I ended up running a code like this one on https://opensource.org/licenses/alphabetical (remove .slice(0, 3) to map it onto all links):

var $$ = (x) => ([...document.querySelectorAll(x)])
var fetchAndParse = async (url) => { let div = document.createElement("div"); div.innerHTML = await (await fetch(url)).text(); return div }
var waitTimeout = async (duration) => { return new Promise((accept) => setTimeout(accept, duration)) }
var licenseArray = await Promise.all($$("#main a[href]").slice(0, 3).map(async (anchor, k) => {
  let text = await fetchAndParse(anchor.href).then(div => div.querySelector("#main").textContent.replace(/\s+/g, ' ').trim()).catch(error => { console.error(anchor.href, error); return '' })
  return [anchor.href.replace(/^.*\//, ''), anchor.textContent.length, text.length, anchor.textContent, { href: anchor.href, text }]
}))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondittoView Question on Stackoverflow
Solution 1 - JavascriptVladimir JovanovićView Answer on Stackoverflow
Solution 2 - JavascriptbronzehedwickView Answer on Stackoverflow
Solution 3 - Javascriptmahmoud mizView Answer on Stackoverflow
Solution 4 - JavascriptFoxPawView Answer on Stackoverflow
Solution 5 - JavascriptTrần Nguyên KhuyếnView Answer on Stackoverflow
Solution 6 - JavascriptOmar bakhshView Answer on Stackoverflow
Solution 7 - JavascriptMathieu CAROFFView Answer on Stackoverflow