如何使用提取API填充DIV?

Tom*_*son 5 html javascript css fetch

我正在尝试获取页面的html(一旦我可以正常工作,我将在请求的页面中获取特定的Div),然后将此页面打印到我的id="data"div中。我可以在诺言中看到信息,但是我无法访问该信息。

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));
Run Code Online (Sandbox Code Playgroud)
<div id='data'></div>
Run Code Online (Sandbox Code Playgroud)

Nis*_*arg 6

.text()您在响应主体上调用的方法将返回一个Promise。因此访问它的正确方法是通过承诺链。

根据文档

Body mixin的text()方法获取一个Response流,并将其读取完成。它返回一个用USVString对象(文本)解析的承诺。

更新后的代码段应如下所示:

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));
Run Code Online (Sandbox Code Playgroud)
<html>
    <body>
       <div id='data'>
      </div>
      
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)