Search code examples
node.jspostgresqlejsknex.js

Why isn't localhost responding to render?


I am using Knex JS for user authentication in order to get email and password from the user and connect to PostgreSQL to check for authentication.

router.post('/login', async (req, res) => {
  knex.select('email','password').from('users')
    .where('email', '=',req.body.email)
    .then((data) => {
      const isValid = bcrypt.compareSync(req.body.password, data[0].password);
      if (isValid === true) {
        res.render('index-v1');
      }
    });
});

But the render function is not rendering the index ejs file but rather the localhost is not responding. Thanks in advance for the help.


Solution

  • So, as the comments suggest, there are two possible paths not covered by your route, which is apparently leading to a lack of response from the server. Remember, if you don't tell it to respond (with res.render or similar) it won't respond, leaving your client hanging.

    router.post('/login', async (req, res) => {
      try {
        const data = await knex.select('email', 'password')
          .from('users')
          .where('email', '=', req.body.email)
        const isValid = bcrypt.compareSync(req.body.password, data[0].password);
        if (isValid) {
          res.render('index-v1');
          return
        }
    
        res.render('error-page');
      } catch (e) {
        res.render('error-page');
      }
    });
    

    In other words: if the password is incorrect, we still need to respond to the client. If there's some kind of database error (or the user doesn't exist, say) we still need to respond to the client. Exactly how you respond is of course up to you, but that's the kind of structure you need to think about.