使用fetch()返回HTML [英] Returning HTML With fetch()

查看:380
本文介绍了使用fetch()返回HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取文件并返回其HTML.但是,这并不像我想象的那么简单.

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);
    });

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

This returns an object called ReadableByteStream. How do I use this to grab the HTML file content?

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

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);
    });

...它会正确返回JSON.如何获取HTML?

... it returns the JSON correctly. How do I do fetch HTML?

推荐答案

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

You need to use the .text() method, instead of .json(). This converts the byte stream into plain text, which can be parsed by the browser as HTML.

这篇关于使用fetch()返回HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆