如何将Express从MongoDB获取的数据渲染到HTML表格中?
最简单的实现方案
1. 修改服务器端接口,返回实际账户数据
当前接口仅返回状态信息,需要把从MongoDB查询到的账户数组一起返回,这样前端才能拿到数据渲染表格。修改后的代码如下:
app.post('/api/showaccounts', async (req, res) => { try { const accounts = await Account.find({}); console.log(accounts); // 返回状态和账户数据 res.json({ status: "ok", data: accounts }); } catch (error) { // 统一错误返回格式 res.json({ status: "error", message: error.message }); throw error; } });
2. 前端HTML添加JavaScript逻辑渲染表格
在table.html的body标签末尾添加脚本,通过原生fetch请求接口获取数据,遍历数据生成表格行后插入到指定tbody中:
<body> <table> <thead> <tr> <th>Username</th> <th>Balance</th> <th>Name</th> </tr> </thead> <tbody id="data-output"> </tbody> </table> <script> // 页面加载完成后自动请求数据 window.addEventListener('load', async () => { try { const response = await fetch('/api/showaccounts', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({}) }); const result = await response.json(); if (result.status === "ok") { const tbody = document.getElementById('data-output'); // 遍历账户数据生成表格行 result.data.forEach(account => { const tr = document.createElement('tr'); tr.innerHTML = ` <td>${account.username}</td> <td>${account.balance}</td> <td>${account.name}</td> `; tbody.appendChild(tr); }); } else { alert('获取账户数据失败:' + result.message); } } catch (err) { alert('请求接口出错:' + err.message); } }); </script> </body>
关键说明
- 服务器端修改后,接口会返回包含状态标识和账户数组的JSON,前端可根据状态判断请求是否成功
- 前端使用原生
fetchAPI实现请求,无需额外引入第三方库,是最轻量化的实现方式 - 通过DOM操作动态生成表格行,直接插入目标容器,逻辑清晰易维护
内容的提问来源于stack exchange,提问作者LearningC
相关产品推荐
相关产品推荐

