我正在使用带有express.js的react(在router/user.js内部)
router.get("/", function (req, res) {
console.log("this is u" , req.user)
console.log(req.isAuthenticated());
if (req.user) {
res.json({ user: req.user })
} else {
res.json({ user: 'does not exsist' })
}
});
这里console.log显示针对它们的值始终未定义
console.log("this is u" , req.user)
console.log(req.isAuthenticated());
上面的代码总是console.log false,现在我浏览了其他示例,他们提到问题可能是由于您将内容放入server.js(或app.js)中的方式造成的,因此我检查并认为我的问题不是因为这个原因,无论如何,这就是我添加东西的方式
app.use(session({
secret: 'keyboard cat', // -> used to encode and decode the session, the seceret we used will be used to encode to decode
resave: true,
saveUninitialized: true,
}));
app.use(passport.initialize());
app.use(passport.session());
//Session
passport.use(new LocalStrategy(user.authenticate()));
passport.serializeUser(user.serializeUser());
passport.deserializeUser(user.deserializeUser());
如果有人想查看,这是我完整的正确存储库:https://github.com/irohitb/litifier-
现在,有人可以指导我解决这个问题吗?
最佳答案
这是因为登录过程没有被执行。
这会导致 cookie 不被发送,从而导致 cookie 在下一个请求中不被读取,从而导致 req.isAuthenticated()
返回 false
来自passport.js docs ,
Note that when using a custom callback, it becomes the application's responsibility to establish a session (by calling req.login()) and send a response.
解决方案:
由于这看起来像您的注册页面,因此我认为您不需要在此处执行passport.authenticate
。那是为了登录。删除它。
注册新用户后,请执行以下操作:
req.logIn(user, function (err) {
if (err) {
return next(err);
}
return res.json(user) // send whatever you want or redirect
});
关于javascript - req.user 和 Is Authenticated 始终为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51241211/