J.Wujeck
J.Wujeck

Reputation: 280

Retrieve object data ejs

Can you please help me? I can return my data coming from the database but I can't display on the client page.

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

Display data:

<div class="details-container">
    <h1><%= blog.blog_title %></h1>
    <h1><%= blog.blog_description %></h1>
</div>

Console Log

[
  RowDataPacket {
    blog_id: 4,
    blog_title: 'Jordan 1 Black Toe',
    blog_description: 'Dream Shoes'
  }
]

Upvotes: 0

Views: 141

Answers (1)

Mic Fung
Mic Fung

Reputation: 5692

The retrieveBlog() returned array but the frontend is expecting a object.

You can get the first object from blogById by using blogById[0]

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

Upvotes: 1

Related Questions