-1

I used jsonwebtoken package in my express app. Here is the related codes of two routes of my app:

the codes:

router.post('/set-token', function(req, res, next) {
    let userName = req.body.userName;
    let email= req.body.userEmail
    const tokenMe = jwt.sign({ userName, email }, secretKey, { expiresIn: '5h' });
    console.log(tokenMe);
    res.json({"output": tokenMe});
});

router.post('/validate-token', function(req, res, next) {
    console.log(req.body.tokenEmail);
    const tokenHere = req.body.tokenEmail;
    jwt.verify(tokenHere, secretKey, function(err, decoded) {
        if(err) {
            res.redirect("/get-token/err?tokenErr=There are some errors in the server or the verification email in your inbox has some problems. Please go to your dashboard and request for a new verification email later.");
        } else {
            console.log(decoded);
            res.redirect("/dashboard2/information");
        }
        
    })
})

To describe that code, in the /set-token route, I generate a token and save it in tokenMe variable. Then in another request in /validate-token route, that has the same token in his body, I want to verify that token and get the real values of userName and email that made the token. But in the line that I console the result (I mean console.log(decoded)), only get this object:

{ iat: 1677232406, exp: 1677250406 } 

How could I get the values of userName and email? according to the docs, the decoded parameter should contain that values automatically. Is my codes wrong?

To better understand the problem, I put this link that is the link of a YouTube video. It uses the same approach, I mean that it set a token in one route and get the value of email, ... in another route. You can watch the second half of the video to better understand my meaning. I could not know what is wrong with my codes. The video does not use any extra package and the code should be work!

hamid-davodi
  • 1,602
  • 2
  • 12
  • 26

1 Answers1

0

After lots of debugging, I finally found the reason of the problem. req.body.userName and req.body.userEmail that I used in /set-token route were undefined. Thanks to this question I found that I must use body-parser or express.json() and also set the header of my fetch related codes correctly. After doing that corrections, now I can get the real object like this:

{                             
  userName: 'the user-name',   
  email: 'the email of user',
  iat: 1677318832,            
  exp: 1677336832             
} 

                        
hamid-davodi
  • 1,602
  • 2
  • 12
  • 26