Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use fetch API to populate a DIV?

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>
like image 485
Tom Dickson Avatar asked Mar 08 '19 06:03

Tom Dickson


People also ask

How do I return a value from fetch API?

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.

How do I use fetch API to post 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.


1 Answers

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>
like image 96
Nisarg Shah Avatar answered Oct 13 '22 00:10

Nisarg Shah