我正在尝试用 取来 在某个网页中,为了在项目中使用它。我有一个问题需要解决。
代码如下,我使用了一个 取来 访问我的网站 (https:/mynicewebsite.example.com。),可能会设置一些选项(标题……)……。通过使用 document.getElementById(‘bdyID’).innerHTML = await 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。 的浏览器中。
解决方案:
我想通过content-type头,可以在响应对象上调用.json。
const data = await response.json()
const formattedResponse = JSON.stringify(data, null, 2);
document.getElementById('bdyID').innerHTML = formattedResponse;
JSON.stringify有三个参数,第三个参数是空格。https:/developer.mozilla.orgen-USdocsWebJavaScriptReferenceGlobal_ObjectsJSONstringify。
要知道,无论如何你都可以在devtools中看到你的响应好格式。例子有json和预标签。https:/codesandbox.ioscondescending-platform-f6gj6?fontsize=14&hidenavigation=1&主题=dark。
本文来自投稿,不代表实战宝典立场,如若转载,请注明出处:https://www.shizhanbaodian.com/4707.html