【问题标题】:Bearer token undefined不记名令牌未定义
【发布时间】:2018-10-28 16:04:54
【问题描述】:

我正在尝试将 Bearer 令牌添加到我的 POST 路由中。当我通过 Postman 提交 POST 请求时,我得到以下输出:

{
    "success": true,
    "token": "Bearer undefined"
}

这是我的 user.js 代码:

router.post("/login", (req, res) => {
  const email = req.body.email;
  const password = req.body.password;

  //find user by email
  User.findOne({ email }).then(user => {
    //check for user
    if (!user) {
      return res.status(404).json({ email: "user not found" });
    }
    //check password
    bcrypt.compare(password, user.password).then(isMatch => {
      if (isMatch) {
        //user matched
        const payload = { id: user.id, name: user.name, avatar: user.avatar }; //create jwt payload
        //sign token : good for one hour
        jwt.sign(
          payload,
          keys.SecretOrKey,
          { expiresIn: 3600 },
          (err, token) => {
            res.json({
              success: true,
              token: "Bearer " + token
            });
          }
        );
      } else {
        return res.status(400).json({ password: "password incorrect" });
      }
    });
  });
});

// @route  GET api/users/current
// @desc   Return current user
// @access Private route
router.get(
  "/current",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    res.json({ msg: "Success" });
  }
);

module.exports = router;

我不确定问题出在哪里。任何建议表示赞赏。

【问题讨论】:

    标签: node.js express jwt bearer-token


    【解决方案1】:

    请检查一下keys.SecretOrKey 获得的价值

    【讨论】:

    • 感谢 Binayak!我的有效载荷中有:keys.SecretOrKey 而不是 keys.secretOrKey。
    • 我的荣幸。 :) 乐于助人。
    • 谢谢,它帮助我找到了错误所在。
    猜你喜欢
    • 2019-08-03
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 2020-03-21
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多