以下代码是由Node.js + Express + Passport.js开发的应用程序的一部分。有效用户会被重定向到/profile
网址(successRedirect),但req.isAuthenticated
会返回false,req.user
也会undefined
。我无法弄清楚可能是什么原因:
app.post('/login',
passport.authenticate('local', {
successRedirect: '/profile',// <-- a valid user gets redirected to `/profile`
failureRedirect: '/',
failureFlash: true
})
);
app.get('/profile',function(req,res){
console.log('req.user: \n'+req.user)
console.log('req.isAuthenticated(): '+req.isAuthenticated()) // <-- However, the `req.isAuthenticated()` returns false
console.log('req.isAuthenticated: '+req.isAuthenticated)
res.render('profile.ejs',{
/*username: req.user.username*/ // <-- req.user is undefined
});
})
答案 0 :(得分:0)
在需要验证的每条路线上,您都应该使用passport.authenticate中间件,即:
app.get('/profile', passport.authenticate('local'), (req, res) => {
console.log(req.user);
console.log(req.isAuthenticated());
}