0

有人可以向我详细解释为什么 /profile 的路由可以访问用户对象。我目前正在学习 JavaScript 和 NodeJS,您的回答将对我的学习有很大帮助谢谢大家。

app.post('/login',function (req, res) {
        let email = req.body.email;
        let password = req.body.password;
        User.getUserByEmail(email, (err, user) => {
            if (err) throw err;
            if (!user) {
                return res.json({
                    success: false,
                    message: "User not found!"
                });
            }
            User.comparePassword(password, user.password, (err, isMatch) => {
                if (err) throw err;
                if (isMatch) {
                    var token = jwt.sign(user.toJSON(), config.JWT_SECRET, {
                        expiresIn: '15m'
                    });
                    res.json({
                        success: true,
                        token: token,
                        user: {
                            id: user._id,
                            email: user.email
                        }
                    });
                } else {
                    return res.json({
                        success: false,
                        message: "Password incorrect!"
                    });
                }
            })
        });
    });

    app.get('/profile', passport.authenticate('jwt', {
        session: false
    }), (req, res) => {
        res.json({user: req.user});
    });
4

2 回答 2

0

这是因为您的passport.authenticate()呼叫填充userreq.

来自passports.org:

app.post('/login',
  passport.authenticate('local'),
  function(req, res) {
    // If this function gets called, authentication was successful.
    // `req.user` contains the authenticated user.
    res.redirect('/users/' + req.user.username);
  });

你的路由是一样的,只是你的路径和身份验证方法不同。

有关更多信息,请参阅文档:http: //www.passportjs.org/docs/authenticate/

于 2019-02-27T21:16:39.810 回答
0

一些背景

  • 该函数app.get接受一个url一个或多个回调(req, res, next) => {}作为其签名
  • 回调一个接一个地执行。在这些回调中的任何一个中, 您都可以修改req对象,它将“传播”到下一个回调
  • 要从回调切换到下一个,请调用next

在你的情况下

  • 调用passport.authenticate('jwt', {sessions: false})返回一个回调,它在您发送json响应之前执行。
  • 该回调本身对用户进行身份验证,然后将其值“注入”req到对象中。
  • 正如我之前提到的,这req“传播”到下一个回调。这就是为什么当您发送json回复时,它req已经包含user密钥
于 2019-02-27T21:16:55.000 回答