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?
Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.
The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.
The fetch() method returns a promise that can either be resolved or not. Thus, this method always returns a value and the only possible case where it may fail to return anything is a server error.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With