首页 > 解决方案 > 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("")

})

标签: node.js

解决方案


如果您希望将userSubjectsHTML 插入到您的页面中,则必须将其实际插入到您的页面中。您没有显示任何页面 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);
});

变更摘要:

  1. 添加return到循环fetch()内部,.map()以便返回 Promise .map(),它将产生一个 Promise 数组
  2. 在 Promise 数组上使用Promise.all()以等待所有 Promise 完成并获得最终结果。返回该承诺,以便错误也传播到顶层
  3. 将生成的内容插入<div>页面中的 a 中。
  4. 添加一个顶级.catch(),以便您可以捕获您的承诺中的任何错误并将其记录或向用户显示错误。

推荐阅读