0

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.

Karloux
  • 11
  • 4
  • `data` is an object. Is there a specific property of `data` that you wish to render? – 76484 Aug 24 '22 at 18:01
  • I'm trying to display my user's email which is supposed to be stored in the data object. – Karloux Aug 24 '22 at 20:03
  • You should try logging your `data` object to see it's shape. In Handlebars, you can do `{{log data}}`. I suspect you will find you will need your template to look something like: `{{data.email}}`. – 76484 Aug 24 '22 at 20:12
  • Thank you for your answers, {{log data}} gives me [ RowDataPacket { email: 'Fada@icloud.com' } ] in the console and {{data.email}} in exchange shows me nothing at all without error. {{log data.email}} gives me undefined. – Karloux Aug 24 '22 at 20:16

1 Answers1

0

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 : ''
76484
  • 8,498
  • 3
  • 19
  • 30