Improviser 14
Improviser 14

Reputation: 35

Bearer token undefined

I’m trying to add a Bearer token into my POST route. When I submit a POST request through Postman, I’m getting the following output:

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

Here is my user.js code:

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;

I'm not sure where the problem is. Any suggestions are appreciated.

Upvotes: 0

Views: 5881

Answers (1)

user7515414
user7515414

Reputation:

Kindly check once what value you are getting for keys.SecretOrKey

Upvotes: 5

Related Questions