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?
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.
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);
});
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);
});
来源:https://stackoverflow.com/questions/36631762/returning-html-with-fetch