I have a new error with the code below. What I'm trying to do is to build a simple login system, but I have a problem with redirecting res.redirect('/example')
. When I try to redirect users the console.log says that Headers have been already sent. I know that there are other questions similar to this but I'm not able to solve this problem. Please help
The file below is the main controller:
exports.login = function(req, res){ var email = req.body.email, password = req.body.password; User.findOne({email: email, password: password}, function(err,obj) { if(obj){ console.log(obj); console.log('Access approved'); req.session.regenerate(function(){ console.log('New session printed to Sessions DB'); req.session.email = email; res.redirect('/sec'); }); } else if(!email || !password){ console.log('Please insert data'); }else if(err){ console.log('Error'); req.session.regenerate( function(){ req.session.msg = err; res.redirect('/login'); }); } else { console.log('errore not authenticated user'); req.session.msg = err; res.redirect('/login'); } }); };
This is the Routes file:
app.post('/logUser', users.login)
And the node:
app.use('/login', function(req, res) {
res.sendFile('public/login.html', {root: __dirname });
});
Ok, finally I found the solution and it's pretty simple. I need to add next();
to node file, like this:
app.use('/login', function(req, res, next) {
res.sendFile('public/login.html', {root: __dirname });
next();
});
Probably it happen because setting next
I can change headers that have been already sent and finally I can reset it again with res.redirect
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.