Passport.js 通过 Post 请求获取当前登录的用户

我遇到了 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,但没有答案。


阿晨1998
浏览 212回答 1
1回答

慕哥6287543

这是因为用户在您检查时可能没有登录。为确保用户在访问路由时已登录,您应该有一个中间件来为您检查它。如果需要,您可以将其编写为单独的模块并将其导入到您的每条路线中。模块:module.exports = {    EnsureAuthenticated: (req, res, next) => {        if (req.isAuthenticated()) {            return next();        } else {            res.sendStatus(401);        }    }};路线://Destructuring | EnsureAuth Functionconst {    EnsureAuthenticated} = require('../path/to/the/module');//You should get your user hererouter.get('/', EnsureAuthenticated, (req, res) => {console.log(req.user)});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript