简体   繁体   中英

How to redirect another page after successfully login nodejs

I'am trying to sending client to next page when login process is successful done,page is confirm page.but i am geting some error. image screenshot

router.post('/sign_in', urlend, function(req, res) {
  var email = req.body.user_id;
  var password = req.body.password;
  if (email != '' && password != '') {
    user_modell.findOne({
      email: email,
      password: password
    }, function(err, data) {
      if (err) {
        //res.status(500).send();
        console.log('error');
      } else if (!data) {
        console.log('Incorrect User ID or Password');
        return res.end();
      } else {
        res.render("confirm");
      }
    });
  }
  res.end();
});

response.redirect('URL'); is used to redirect request to another page

Code

router.post('/sign_in',urlend,function(req,res){
    var email=req.body.user_id;
    var password=req.body.password;
    if(email!='' && password!=''){      
        user_modell.findOne({email:email,password:password},function(err,data){
            if(err){
                //res.status(500).send();
                console.log('error');
            } else if(!data){
                console.log('Incorrect User ID or Password');
                return res.end();
            }else{
                  res.redirect("/confirm"); 
            }
        });
    }
    res.end();
});

You can use express-redirect package as well.

Explanation for your error

The error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client is because your code tries to send two responses. model.findOne is like a timeout. You pass in a callback and it executes later. This means that res.end() sets the headers and sends a response. Then later, your callback is called and you try to send another response.

Think of it like a telephone conversation: someone calls you and tells you their email/password, you say "Hold on a second, I'll just check", then you hang up the phone and pick up a notebook of known emails/passwords. Then when you figure out what you want to respond with, you pick the phone back up, but there's nobody listening, cause you cut them off when you hung up the phone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM