1

I need to fetch foo from the query below:

exports.get = function(id, cb) {
    sql = 'SELECT `sidebar`, `test` FROM users WHERE `id` = "' + id + '"';
    con.query(sql, function(err, foo) {
      if (err) { return cb(err) }
      else { return cb(foo) };
    });
}

Then render foo on my app.js like this:

app.get('/dashboard', ensureLoggedIn('/login'),
  function(req, res) {
    const id = req.session.passport.user;
    const foo = db.defaults.set(id) //db.defaults.set calls the query
    console.log(foo); //prints undefined
    res.render('dashboard', { foo:foo });
});

This was my latest attempt:

app.get('/dashboard', ensureLoggedIn('/login'),
  function(req, res, next) {
    const id = req.session.passport.user;
    db.defaults.get(id, function(err, foo) {
      if (err) return next(err);
      res.render('dashboard', {foo:foo});
      //also tried:
      //return res.render('dashboard', {foo:foo});
    });

The attempt above doesn't render the page at all. The html loads as:

[object object]

What am I missing?

1 Answer 1

1

You're trying to render server side a template asynchronously (after fetching the data) and you can't do that.

What you can do is send synchronously the template to the client and then expose an endpoint to fetch those data and modify the page accordingly (on the client).

app.get('/dashboard', ensureLoggedIn('/login'), function(req, res) {
  res.render('dashboard');
});

app.get('/fetchdata', function (req, res, next) {
  const id = req.session.passport.user;
    db.defaults.get(id, function(err, foo) {
      if (err) return next(err);
      res.send(foo);
    });
})
Sign up to request clarification or add additional context in comments.

2 Comments

What would the endpoint for /fetchdata look like on dashboard.ejs?
you need to remove the foo parameter on the .ejs file cause that won't work, you can make the api call to /fetchdata in your js after the page has loaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.