node.js - Node.js关于如何在html中成功显示信息的问题
问题描述
目标是显示学生注册的科目。
这行代码将显示从
mainContent.innerHTML =
<div class="col-md-12">
<section class="jumbotron my-5 bg-white">
<h5 class="text-center">First Name: <b style="text-transform: uppercase;">${jsonData.firstName}</b> | Last Name: <b style="text-transform: uppercase;">${jsonData.lastName}</b> | Email: <b style="text-transform: uppercase;">${jsonData.email}</b> | Mobile No: <b style="text-transform: uppercase;">${jsonData.mobileNo}</b></h5>
<table class="table text-center">
<tr>
<th>Course Name </th>
<th>Enrolled On </th>
<th>Status </th>
<tbody>${userSubjects}</tbody>
</tr>
</table>
</section>
</div>
我成功地能够使用 console.log 在控制台选项卡上显示数据(主题名称)。但是,将代码直接提取到我的 JS 上的 HTML 标记是不允许的。它什么也不显示或未定义。
fetch("http://localhost:4000/api/users/details", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
}).then(res => res.json())
.then(jsonData => {
if (jsonData) {
let userSubjects = jsonData.enrollments.map(subject => {
fetch(`http://localhost:4000/api/courses/${subject.courseId}`).then(res => res.json()).then(subjectData => {
return (`
<tr>
<td>${subjectData.name}</td>
<td>${subject.enrolledOn}</td>
<td>${subject.status}</td>
</tr>
`
)
})
}).join("")
})
解决方案
如果您希望将userSubjects
HTML 插入到您的页面中,则必须将其实际插入到您的页面中。您没有显示任何页面 HTML,因此我将仅显示一个虚构的示例。此外,您.map()
创建了一系列承诺,因此您必须等待所有这些承诺解决。
如果你的页面中有这个:
<div id="content"></div>
然后,您可以将动态检索的数据和生成的 HTML 插入到页面中的该 div 中,如下所示:
fetch("http://localhost:4000/api/users/details", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
}).then(res => res.json())
.then(jsonData => {
if (jsonData) {
let userSubjectPromises = jsonData.enrollments.map(subject => {
return fetch(`http://localhost:4000/api/courses/${subject.courseId}`).then(res => res.json()).then(subjectData => {
return (`
<tr>
<td>${subjectData.name}</td>
<td>${subject.enrolledOn}</td>
<td>${subject.status}</td>
</tr>
`
)
})
});
return Promise.all(userSubjectPromises).then(results => {
const newHtml = results.join("");
document.getElementById("content").innerHTML = newHtml;
});
}).catch(err => {
// do something with an error here
console.log(err);
});
变更摘要:
- 添加
return
到循环fetch()
内部,.map()
以便返回 Promise.map()
,它将产生一个 Promise 数组 - 在 Promise 数组上使用
Promise.all()
以等待所有 Promise 完成并获得最终结果。返回该承诺,以便错误也传播到顶层 - 将生成的内容插入
<div>
页面中的 a 中。 - 添加一个顶级
.catch()
,以便您可以捕获您的承诺中的任何错误并将其记录或向用户显示错误。
推荐阅读
- javascript - accessing children of divs using tab
- ruby - 使用匹配的关键字参数直接将结构传递给方法
- java - 为什么我的应用程序因 NullPointerException 而崩溃
- function - 在嵌套 if 语句中调用函数
- python - 当我使用请求 API 调用时出现 Python MemoryError
- node.js - 如何在 AWS 上为 NodeJS 项目设置持续部署管道?
- python - 写入文件时如何摆脱\n?
- javascript - Javascript 相当于 LEFT OUTER JOIN 在 WHERE 子句中带有 NULL
- docker - Dockerfile: $HOME 已设置,但在使用它定义其他环境变量时变为空白
- python - Selenium 不在网页上执行 javascript