ABE_Mark45
ABE_Mark45

Reputation: 31

Why is myToken variable is always undefined?

var fs = require('fs');
var jwt = require('jsonwebtoken');

var secret = fs.readFileSync('secret.key', 'utf8');

var myToken = jwt.sign({foo : 'bar'}, secret, {expiresInMinutes : 1440}, function(err, token) {
      console.log(token);
});

Here is my code. The problem is that myToken is always undefined. So, Where is the problem here ?

Upvotes: 2

Views: 109

Answers (1)

xdazz
xdazz

Reputation: 160833

You are using asynchronously way. So the token is got in the callback function, will not be returned by jwt.sign function.

jwt.sign({foo : 'bar'}, secret, {expiresInMinutes : 1440}, function(err, token) {
      console.log(token);
});

If you don't use asynchronously way, then it should be:

var myToken = jwt.sign({foo : 'bar'}, secret, {expiresInMinutes : 1440});

Chose either style but not both.

Upvotes: 3

Related Questions