首页 > 解决方案 > 检索对象数据 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'
  }
]

标签: node.jsexpressejs

解决方案


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!'
      });
  }
});

推荐阅读