javascript - 获取后如何获得良好的显示?
问题描述
我正在尝试在某些网页中获取,以便在项目中使用它。我有一个问题需要解决。
代码如下,我使用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时显示的屏幕截图:
解决方案
我想通过内容类型标头,您可以在响应对象上调用 .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
推荐阅读
- spring - mongoTemplate.upsert 不保存 _class
- laravel - xhr 后 livewire 不更新变量
- linux-kernel - ftrace:通过GPIO输出
- javascript - 如何使用 ffmpeg 通过媒体记录器 api 从块中创建视频文件 webm
- c# - 在 c# 中通过 : 拆分字符串,但忽略 :: 和任何括号
- java - Hibernate 读取和更新大数据
- amazon-web-services - Beanstalk 升级到“运行 Tomcat 8.5 Corretto 8 的 64 位 Amazon Linux 2 v4.1.2”后缺少 Tomcat 日志 (catalina.out)
- c - C用分隔符加入char**
- node.js - findOneAndUpdate 未在环回中返回新文档
- swift - 在 API 函数调用之后 SWIFT 设置 UI 值