我遇到了 Passport.js 的问题,我想从 Post 请求中获取当前登录的用户信息并处理一些内容。当我 console.log(req.user) 出现时,它显示为“未定义”。设置和身份验证一切正常,我还可以使用从第一个代码片段中看到的 Get 请求检索用户信息。router.get('/', function(req , res){ console.log("The current logged in user is: " + req.user.first_name); res.render('index.ejs' , { user: req.user });});^ 按预期返回用户名router.post('/testPost' ,function(req , res){ console.log("The current logged in user is: " + req.user); res.json({ status: "success" });});^即使用户登录也返回未定义。两年前,我在这里看到了同样的问题How to get req.user in POST request using passport js,但没有答案。
1 回答

慕哥6287543
TA贡献1831条经验 获得超10个赞
这是因为用户在您检查时可能没有登录。
为确保用户在访问路由时已登录,您应该有一个中间件来为您检查它。
如果需要,您可以将其编写为单独的模块并将其导入到您的每条路线中。
模块:
module.exports = {
EnsureAuthenticated: (req, res, next) => {
if (req.isAuthenticated()) {
return next();
} else {
res.sendStatus(401);
}
}
};
路线:
//Destructuring | EnsureAuth Function
const {
EnsureAuthenticated
} = require('../path/to/the/module');
//You should get your user here
router.get('/', EnsureAuthenticated, (req, res) => {
console.log(req.user)
});
添加回答
举报
0/150
提交
取消