title: nodejs express login fail
body: <p>I am using express session to login user.</p>
  
  <h2>Middleware:</h2>
  
  <pre><code>var requireLogin = function (req, res, next) {
      if (req.session.user) {
          next();
      } else {
          res.redirect('/'); 
      }
  }
  </code></pre>
  
  <h2>Route:</h2>
  
  <pre><code>app.post('/login', requireLogin, routes.login);
  
  exports.login = function (req, res) {
      var query = {username:req.body.username, password:req.body.password};
  
      User.find(query, function (err, data) {
          if (data) {
              req.session.user = data;
              console.log(data);
              res.redirect('/home');
          } else {
              console.log(err);
              res.redirect('/');
          }
      });
  };
  </code></pre>
  
  <p>When I enter a wrong username and password, it still redirect to home, but the data is <code>null</code>.</p>