我正在使用passportjs在expressjs中进行身份验证。这是我的login.js代码
passport.use(new LocalStrategy(
function(username, password, done) {
//console.log(username);
Usercollection.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
else{
return done(null, user);
}
// if (!user.validPassword(password)) {
// return done(null, false, { message: 'Incorrect password.' });
// }
});
}
));
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
router.post('/', passport.authenticate('local', {
successRedirect: '/automation-panel',
failureRedirect: '/'
})
);
和users.js是
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
if (req.isAuthenticated()){ next(); }else {res.redirect('/');}
// var sess = req.session;
// if(sess.username != null){
// // res.send("hello "+ sess.username);
// console.log(req.user.username);
// }
// else{
// req.redirect('/');
// }
// res.sendFile("fileUpload.html");
// res.send("hello success");
res.render('users/index', { title: 'Express'});
});
module.exports = router;
并且详细错误是
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:690:11
答案 0 :(得分:1)
router.get('/', function(req, res, next) {
if (req.isAuthenticated()) {
return res.render('users/index', { title: 'Express'});
}
else return res.redirect('/');
});
如果问题仍然存在,你会以某种方式进行另一次重定向。所以也许这就是问题。
router.post('/', passport.authenticate('local', {
successRedirect: '/automation-panel',
failureRedirect: '/'
})
);
答案 1 :(得分:0)
router.get('/', function(req, res, next) {
if (req.isAuthenticated()){
res.render('users/index', { title: 'Express'});
}else {
// Remove Below line. otherwise it will create infinite redirect loop.
res.redirect('/');
}
});