使用 fetch() 返回 HTML

新手上路,请多包涵

我正在尝试获取文件并返回它的 HTML。然而,它并不像我想象的那么简单。

     fetch('/path/to/file')
    .then(function (response) {
      return response.body;
    })
    .then(function (body) {
      console.log(body);
    });

这将返回一个名为 ReadableByteStream 的对象。我如何使用它来抓取 HTML 文件内容?

如果我将 /path/to/file 的内容更改为 JSON 字符串,并将以上内容更改为:

     fetch('/path/to/file')
    .then(function (response) {
      return response.json();
    })
    .then(function (json) {
      console.log(json);
    });

…它正确返回 JSON。我如何获取 HTML?

原文由 ditto 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 3.2k
2 个回答

您需要使用 .text() 方法,而不是 .json() 。这会将字节流转换为纯文本,浏览器可以将其解析为 HTML。

原文由 bronzehedwick 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 fetch 下载 html,然后使用 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);
    });

原文由 Vladimir Jovanović 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题