简体   繁体   English

如何使用 NodeJS 将 jwt 令牌从控制器传递到路由器

[英]How to pass jwt token from controller to router using NodeJS

Hello developers the question is simple,你好开发人员,问题很简单,
I have generated a jwt token in my Login function using the jwt.sign() , and I have Model/Controller/Router Architecture,我使用jwt.sign()在我的登录函数中生成了一个jwt令牌,并且我有模型/控制器/路由器架构,
so the question is : How can I pass the generated token from the Login controller function to the router.所以问题是:如何将生成的令牌从登录控制器功能传递到路由器。
I've tried many times to assign the token to a const variable to send it throw an object and send it to the router files, but when I go out from the jwt.sign() function it shows me that is undefined .我已经多次尝试将令牌分配给一个 const 变量,以将其发送给一个对象并将其发送到路由器文件,但是当我从jwt.sign()函数中退出时,它显示我是undefined
PS : I'am just using NodeJS and fastify in the backend and send http request with Postman am not using any framework in the front-end PS:我'只是用NodeJSfastify在后端和发送HTTP请求与Postman我不使用在前端任何框架
There is some code than can help you to understand my situation :有一些代码可以帮助您了解我的情况:

UserRouter.js: (Login route) : UserRouter.js:(登录路由):

{
    method: "POST",
    url: "/api/login",
    handler: (req, res) => {
      UserController.login(req.body.email, req.body.password)
        .then(result => {
          //res.header("Access-Control-Allow-Origin", URL);
          if (result.statusCode == 200) {
            res.send({
              status: 200,
              error: null,
              response: result.Message
              //token: result.token
            });
          } else if (result.statusCode == 401) {
            res.send(
              JSON.stringify({
                status: 401,
                error: null,
                response: result.Message
              })
            );
          }
        })
        .catch(err => {
          //res.header("Access-Control-Allow-Origin", URL);
          res.send(JSON.stringify({ status: 300, error: err, response: null }));
        });
    }
  }

User Controller :用户控制器:

exports.login = async (user_email, password) => {
  try {
    console.log("Login into API");
    const email = user_email.toLowerCase();
    const user = await User.findOne({ email });

    if (user) {
      console.log(" Hashed Passwd ", user.password);
      console.log("User Passwd", password);

      let result = await bcrypt.compareSync(password, user.password);
      if (result) {
        // Tryed also with const = await jwt.sign()
        jwt.sign({ user }, "secretkey", (err, token) => {
          if (err) throw err;
          console.log("The Token is", token);
        });
        return {
          Message: "Login success",
          statusCode: 200
          //token: token
        };
      } else {
        return { Message: "Incorrect password", statusCode: 401 };
      }
    } else {
      return { Message: "ERROR" };
    }
  } catch (err) {
    throw boom.boomify(err);
  }
};

if you look at the package readme , you'll find jwt.sign returns nothing when a callback is provided.如果您查看包readme ,您会发现jwt.sign在提供回调时jwt.sign返回任何内容。

So what you should do is:所以你应该做的是:

const token = jwt.sign({ user }, "secretkey");

That would make the library work synchronously and return the token.这将使库同步工作并返回令牌。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM