Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js node js jwt如何将令牌传递给其他路由,以便稍后检查记录的用户信息_Node.js_Express_Mongoose_Jwt - Fatal编程技术网

Node.js node js jwt如何将令牌传递给其他路由,以便稍后检查记录的用户信息

Node.js node js jwt如何将令牌传递给其他路由,以便稍后检查记录的用户信息,node.js,express,mongoose,jwt,Node.js,Express,Mongoose,Jwt,我正在为自己创建一个应用程序。所以现在我需要使用jsonwebtoken对用户进行身份验证,我知道如何创建一个令牌来对用户进行身份验证。因此,实际上我需要知道如何在以后使用用户登录系统时创建的令牌检索登录用户的信息。我到处寻找一个好答案,但找不到一个好答案 apiRoutes.post('/authenticate', function(req, res) { // find the user User.findOne({ name: req.body.name }, func

我正在为自己创建一个应用程序。所以现在我需要使用jsonwebtoken对用户进行身份验证,我知道如何创建一个令牌来对用户进行身份验证。因此,实际上我需要知道如何在以后使用用户登录系统时创建的令牌检索登录用户的信息。我到处寻找一个好答案,但找不到一个好答案

apiRoutes.post('/authenticate', function(req, res) {

// find the user
  User.findOne({
    name: req.body.name
  }, function(err, user) {

    if (err) throw err;

    if (!user) {
      res.json({ success: false, message: 'Authentication failed. User not found.' });
    } else if (user) {

      // check if password matches
      if (user.password != req.body.password) {
        res.json({ success: false, message: 'Authentication failed. Wrong password.' });
      } else {

        // if user is found and password is right
        // create a token
        var token = jwt.sign(user, app.get('superSecret'));

        // return the information including token as JSON
        res.json({
          success: true,
          message: 'Enjoy your token!',
          token: token
        });
      }
    }
  });
});
这是用户登录和令牌创建过程

下面的路由器我需要检索所有用户信息,如果用户登录到系统并创建了令牌

apiRoutes.get('/users', function(req, res) {
  if(!loggedinUser){
    //throw err
}
else {
  User.find({}, function(err, users) {
    res.json(users);
   });
  });
}
所以请帮我理解这一点,我希望你们能给我一个好的答案


谢谢

生成授权令牌后,您需要通过客户端在所有请求中发送该令牌。 在服务器端,您需要在本例中实现一个身份验证中间件,您将检查身份验证令牌。并进一步处理该请求 检查此链接

将用户登录令牌添加到
req.session.token
中,然后在jwt中间件中检查它