node.js - 检索对象数据 ejs
问题描述
你能帮我么?我可以返回来自数据库的数据,但无法在客户端页面上显示。
router.get('/details', async (req, res, next) => {
try {
const { id } = req.query;
const blogById = await retrieveBlog(id);
res.render('details', {
blog: blogById
});
} catch (error) {
console.log("GET /details/:id: ", error);
res.status(500).json({
status: 'Error retrieving data by id!'
});
}
});
显示数据:
<div class="details-container">
<h1><%= blog.blog_title %></h1>
<h1><%= blog.blog_description %></h1>
</div>
控制台日志
[
RowDataPacket {
blog_id: 4,
blog_title: 'Jordan 1 Black Toe',
blog_description: 'Dream Shoes'
}
]
解决方案
retrieveBlog() 返回数组,但前端需要一个对象。
您可以使用 blogById[0] 从 blogById 获取第一个对象
app.get('/details', async (req, res, next) => {
try {
const { id } = req.query;
const blogById = await retrieveBlog(id);
const firstBlog = blogById[0] // { blog_title: '123', blog_description: '123'
res.render('details', {
blog: firstBlog
});
} catch (error) {
console.log("GET /details/:id: ", error);
res.status(500).json({
status: 'Error retrieving data by id!'
});
}
});
推荐阅读
- windows - 在bat中处理文本文件时如何不丢失特殊字符?
- javascript - 在 php 文件上使用 js 的计时器使输入和 textarea 样式返回为默认值
- html - 如何检查按钮是否被第二次点击?
- asp.net - asp.net中继器控件内的引导网格
- arrays - 如何使用 Observable 填充 Angular Mat-Table
- javascript - Making a conditional function more efficient
- python - Import two modules in Main file, and call methods in them from each other
- html - 如何使用@media 修改动画
- json - Process multi-level nested escaped JSON strings inside JSON with fluentd
- ssis - SSIS Count duplicates