Returning HTML With fetch()
Solution 1:
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:
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:
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:
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.