Matoy
Matoy

Reputation: 1818

method in express js get() - returns undefined

I have this Node.js code that should, using Express.js http get, decode my jwt token from my http auth header.

When I write the code of decodeToken() inside of my express js get() method, everything works fine.

When I extract it to outside method (decodeToken() method) I get that undefined value from this method. Mind you, when this code was hard coded inside of the method get() it works.

Why is that, the async nature of Node.js? Does the method finish after the get() method was supposed to assign the token?

If I will use promises, will it solve that?

var jwtCheck = expressJwt({
        secret: "some secret"

});

app.use('/test', jwtCheck);

app.get('/test', function (req, res) {

    var token = req.get('Authorization').split("Bearer ")[1];

    var information = decodeToken(token)
    console.log("information: "+information);
    if (information!=null) {
        res.json(information);
    }
    else {
        res.json('Failed to authenticate token.');
    }
});

var decodeToken = function (token) {
       console.log(token);
    jwt.verify(token, secret, function (err, decoded) {
        if (err) {
            console.log('Failed to authenticate token.');
            return null;
        } else {

            return (decoded);
        }
    });
}

var getToken = function (req) {
    return req.get('Authorization').split("Bearer ")[1];
}

Upvotes: 0

Views: 519

Answers (1)

Ryan
Ryan

Reputation: 5973

jwt.verify is async because you pass a callback to it so anything that calls it needs to handle that. You could look at promises to clean up the logic a little bit but just using the code you have you could modify it like this:

var jwtCheck = expressJwt({
        secret: "some secret"

});

app.use('/test', jwtCheck);

app.get('/test', function (req, res) {

    var token = req.get('Authorization').split("Bearer ")[1];

    // pass callback to decodeToken that gets called after the token is verified
    decodeToken(token, function(information) {
      // this function won't execute until decodeToke calls it as `next()`
      console.log("information: "+information);
      if (information!=null) {
          res.json(information);
      }
      else {
          res.json('Failed to authenticate token.');
      }
    })
});

// accept `next` callback
var decodeToken = function (token, next) {
    console.log(token);
    jwt.verify(token, secret, function (err, decoded) {
        if (err) {
            console.log('Failed to authenticate token.');
            return next(null);
        } else {

            return next(decoded);
        }
    });
}

var getToken = function (req) {
    return req.get('Authorization').split("Bearer ")[1];
}

Upvotes: 1

Related Questions