首页 > 解决方案 > 获取后如何获得良好的显示?

问题描述

我正在尝试在某些网页中获取,以便在项目中使用它。我有一个问题需要解决。

代码如下,我使用fetch访问我的网站(https://mynicewebsite.example.com),可能设置一些选项(标题 ....)...通过使用document.getElementById('bdyID')。 innerHTML = 等待 response.text(); 我在浏览器中显示网站的内容 ( https://mynicewebsite.example.com )。但是这种做法将整个文本显示为一个长的连续字符串。当有人直接访问它时,如何获得一个漂亮的 HTML 显示来显示该站点,因为它通常出现在浏览器中。

这里的代码:

<!DOCTYPE html>
<html>
<head>
</head>
<body id='bdyID'>
<script>
   const makeFetchCall = async () => {
      const response = await fetch('https://mynicewebsite.example.com', {
         method: 'GET',
         headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer blahfblahdblahzblah',
            //..... // possibly some other things
         }
      });

      document.getElementById('bdyID').innerHTML = await response.text();
   }

   makeFetchCall();
</script>
</body>
</html>

这是上面代码显示的屏幕截图:

在此处输入图像描述

这是在浏览器中直接查看https://mynicewebsite.example.com时显示的屏幕截图:

在此处输入图像描述

标签: javascriptjsonfetch-api

解决方案


我想通过内容类型标头,您可以在响应对象上调用 .json 。

const data = await response.json()
const formattedResponse = JSON.stringify(data, null, 2);
document.getElementById('bdyID').innerHTML = formattedResponse;

JSON.stringify 采用三个参数。第三个参数是空间https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

请注意,无论如何您都可以在格式正确的开发工具中看到您的响应。带有 json 和 pre 标签的示例:https ://codesandbox.io/s/condescending-platform-f6gj6?fontsize=14&hidenavigation=1&theme=dark


推荐阅读