0

i'm trying to redirect a user to a page after checking his credentials through a post method. the thing is the page after the res.redirect function keeps trying to redirect but never does.


app.post('/login', function (req, res) {

  MongoClient.connect(url, function(err, db){

    if (err) throw err;
    var dbo = db.db("DATABASE");

    var username = req.body.username;
    var password = req.body.password;


    dbo.collection("DATABASE").findOne({username: username, password: password}, function(err, user){
      if(err){
        console.log(err);
        res.status(500).send();
        db.close();
      }
      if(!user){
        res.status(404).send();
        db.close();

      }else{
          console.log("gets here");
        app.get('/', function(req, res){
          res.redirect('/views/heap')

         });
      }
    })
  }); 
});

the console.log("gets here"); works perfectly fine but the redirect keeps on trying but never loading

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
NeoK
  • 3
  • 2
  • Whats the `app.get('/', fu..` line? – Lawrence Cherone Apr 20 '19 at 02:40
  • Not related to the problem in the question, but "connecting to a database **within** each request" is simply **really bad**. Instead you should learn how to share the connection around your modular code. See : [How to properly reuse connection to Mongodb across NodeJs application and modules](https://stackoverflow.com/q/24621940/2313887) – Neil Lunn Apr 20 '19 at 03:15

1 Answers1

0

Change:

console.log("gets here");
app.get('/', function(req, res){
  res.redirect('/views/heap')

 });

To:

console.log("gets here");
res.redirect('/views/heap');
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • i changed the code but i get this error message: Cannot GET /views/heap.html – NeoK Apr 20 '19 at 02:52
  • then the route doesn't exist, shouldn't it be `res.redirect('/login')`? – Lawrence Cherone Apr 20 '19 at 02:54
  • sidenote, you should also return on not found (first if statement) else your get headers already sent – Lawrence Cherone Apr 20 '19 at 02:56
  • thanks for your reply, it really helped, if I may also ask, what do you mean that i need to return on not found? – NeoK Apr 20 '19 at 21:38
  • np, I mentioned it as you have 2 if blocks, once/if the first one fires because of the error, so will the `if(!user){` one as user wont be set, then your status()/send()'ing twice, which your not after, so need to return. – Lawrence Cherone Apr 20 '19 at 21:41