Search code examples
mysqlnode.jshandlebars.js

How to display MySQL data in an html page ? I can't view the result


Hello dear community, I have the following problem:

I use nodejs with mysql, express and handlebars.

I am trying to send my MySQL data by an express query (router.get(/chat) from page.js ({data: results})

    router.get('/tchat', authController.isLoggedIn, (req, res) => {
  console.log(req.user);
  if( req.user ) {
    db.query("SELECT email from users WHERE name = ?", ["Fada"], function (err, results) {
      if(err) throw err;
      res.render('tchat', {
        user: req.user,
        data: results
      });
    })
  } else {
    res.redirect('/login');
  }
  
})

The mysql data is sent, but when I retrieve it on my tchat.hbs on the client side, it shows me [Object object] instead of my email. How can I fix this?

I retrieve the data with

<p>{{data}}</p>

tchat.hbs :

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="tchat.css">
    <title>Document</title>
</head>
<body>
    <p id="pp">{{user.name}}</p>
    <div>
        <ul id="messages"></ul>
        <input id="m" /> <button onclick="send()" id="btn">Send</button>
    </div>

    <p>unordered list</p>
    <p>{{data}}</p>
    <script src="https://cdn.socket.io/4.4.1/socket.io.min.js" integrity="sha384-fKnu0iswBIqkjxrhQCTZ7qlLHOFEgNkRmK2vaO/LbTZSXdJfAu6ewRBdwHPhBo/H" crossorigin="anonymous"></script>
    <script src="/test.js"></script>
</body>
</html>

Thank you for your answers.


Solution

  • I search for "RowDataPacket" and found this StackOverflow post.

    It looks like results is an array of RowDataPacket objects.

    Therefore, in your /tchat GET handler, you should be able to access the email like:

    data: results[0].email
    

    And then the {{data}} in your template should work.

    Additionally, it would be wise to add some protection for the case when your database query returns no rows.

    data: results.length ? results[0].email : ''