You need to enable JavaScript to run this app. Node.js开发中如何解决学生选课信息在HTML显示为空或undefined问题
优惠活动
大模型
产品
解决方案
定价
更多

Node.js开发中如何解决学生选课信息在HTML显示为空或undefined问题

问题修复说明

根因

  • 你代码中嵌套的fetch是异步API,map遍历后得到的是由Promise实例组成的数组,而非你预期的HTML字符串数组,直接调用join('')自然无法得到正确的渲染内容;同时原代码没有在异步请求完成后触发页面赋值逻辑,也是内容不展示的原因之一。
  • 额外修复了原HTML结构的小问题:表头th没有用thead包裹、tbody错误放在了表头tr内部的语法错误。

修复后代码

fetch("http://localhost:4000/api/users/details", {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
    }
}).then(res => res.json())
.then(async jsonData => {
    if (jsonData) {
        // 收集所有课程详情的异步请求
        const subjectRequestList = 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>
                    `
                })
        })
        // 等待所有请求完成后拼接HTML字符串
        const userSubjects = (await Promise.all(subjectRequestList)).join("")
        // 赋值渲染页面
        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">
                <thead>
                    <tr>
                        <th>Course Name </th>
                        <th>Enrolled On </th>
                        <th>Status </th>
                    </tr>
                </thead>
                <tbody>${userSubjects}</tbody>
            </table>
            </section>
        </div>`
    }
})

内容的提问来源于stack exchange,提问作者Mark Willow Aldave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 20:24:07