gpt4 book ai didi

javascript - 身份验证 ExpressJS -> PassportJs : Error: Can't set headers after they are sent

转载 作者:太空宇宙 更新时间:2023-11-04 00:52:16 25 4
gpt4 key购买 nike

我正在使用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

最佳答案

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: '/'
})
);

关于javascript - 身份验证 ExpressJS -> PassportJs : Error: Can't set headers after they are sent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31875271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com