javascript - req.user 和 Is Authenticated 始终为 false

标签 javascript node.js reactjs express passport.js

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

相关文章:

node.js - 是什么阻止我的 AngularJs 2 应用程序运行检查器中显示的命令?

javascript - 更改reactJs父组件中的状态并不会更改react子组件中的props

javascript - 如何在 react 中获取列表上的点击事件(自动完成)?

JavaScript 按位 NOT ~ 不会产生相同的结果

javascript - 函数会输出 nan 而不是数字,为什么?

node.js - 在 Heroku 调度程序中使用 session

reactjs - React Native - 将选项allowNamespaces传递给babel typescript 插件

javascript - 使用 Angular、Javascript 从表单字段(电子邮件、密码)获取和存储数据,无需用户单击按钮

javascript - ASP.NET 页面加载完成后运行 javascript 函数

node.js - 谷歌通讯录 API nodejs