I am trying to fetch the html of a page (once I can get this working I will be fetching a specific Div in the requested page) then print this page in to my id="data"
div. I can see the information coming through in the promise but I am unable to access that information.
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://www.booking.com"; // site that doesn’t send Access-Control-*
fetch(proxyurl + url) // https://cors-anywhere.herokuapp.com/https://example.com
.then(response => response)
.then(data => {
console.log(data.text());
return document.getElementById('data').innerHTML = data.text();
})
.catch((err) => console.log("Can’t access " + url + " response. Blocked by browser?" + err));
<div id='data'></div>
The Fetch API allows you to asynchronously request for a resource. 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.
POST request using fetch API: To do a POST request we need to specify additional parameters with the request such as method, headers, etc. In this example, we'll do a POST request on the same JSONPlaceholder and add a post in the posts. It'll then return the same post content with an ID.
The .text()
method you invoke on response body returns a promise. So the proper way to access it would be through the promise chain.
As per the documentation:
The text() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with a USVString object (text).
Here's how your updated snippet should look like:
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://www.booking.com"; // site that doesn’t send Access-Control-*
fetch(proxyurl + url) // https://cors-anywhere.herokuapp.com/https://example.com
.then(response => response.text())
.then(html => {
// console.log(html);
document.getElementById('data').innerHTML = html;
})
.catch((err) => console.log("Can’t access " + url + " response. Blocked by browser?" + err));
<html>
<body>
<div id='data'>
</div>
</body>
</html>
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