如何将Mongo数据库中的数据以美观格式渲染展示到HTML网页中
实现步骤
1. 安装并配置模板引擎(以新手友好的EJS为例)
首先安装EJS依赖:npm install ejs
在Express入口文件(通常是app.js/index.js)中添加模板引擎配置:
// 放在其他app.use全局配置之前 app.set('view engine', 'ejs') // 模板文件默认存放在项目根目录的views文件夹,需手动新建该文件夹 app.set('views', './views')
2. 修改路由逻辑,替换返回方式
调整你的路由代码,将res.json替换为res.render传递数据:
app.get('/goalkeepers', (req, res) => { Transfer.find({}, (err, found)=>{ if (err) { console.log(err); res.status(500).send('数据查询失败') } else { // 第一个参数为views文件夹下的模板文件名(无需加.ejs后缀) // 第二个参数为传递给模板的数据集,此处将查询到的found数组命名为goalkeepers传入 res.render('goalkeepers', { goalkeepers: found }) } }) })
3. 编写模板文件实现美观展示
在新建的views文件夹中创建goalkeepers.ejs文件,可参考如下示例编写,根据你的实际数据字段调整内容和样式:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>门将数据列表</title> <style> table { border-collapse: collapse; width: 90%; margin: 30px auto; } th, td { border: 1px solid #e0e0e0; padding: 10px; text-align: left; } th { background-color: #f8f9fa; font-weight: 600; } tr:hover { background-color: #f5f7fa; } h1 { text-align: center; margin-top: 30px; color: #333; } </style> </head> <body> <h1>门将数据列表</h1> <table> <thead> <tr> <!-- 此处列名替换为你的Transfer集合实际存储的字段名 --> <th>姓名</th> <th>年龄</th> <th>所属俱乐部</th> <th>扑救成功率</th> <th>出场次数</th> </tr> </thead> <tbody> <!-- EJS循环遍历数据语法 --> <% goalkeepers.forEach(item => { %> <tr> <td><%= item.name %></td> <td><%= item.age %></td> <td><%= item.club %></td> <td><%= item.saveRate %>%</td> <td><%= item.playedCount %></td> </tr> <% }) %> </tbody> </table> </body> </html>
4. 启动服务测试
重启Express服务后访问/goalkeepers路由,即可看到格式化的展示页面,可自行调整CSS样式匹配你的设计需求。
内容的提问来源于stack exchange,提问作者crackahack
相关产品推荐
相关产品推荐

