Monday, 22 May 2017

Node.js express middleware 'express-jwt' cannot get cookies before the request actually hit the url handler

Like I described in the title, Node.js express middleware express-jwt cannot get the req.cookies before the request actually hit the url handler, like the below code:

app.use(cookieParser());

app.use(expressJWT({
  secret: new Buffer(global.JWT_GATE_OPTS.strSecret),
  credentialsRequired: true,
  getToken: (req) => {
    console.log(777)
    console.log(req.cookies) // Here the req.cookies is always '{}'
    if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
      return req.headers.authorization.split(' ')[1];
    } else if (req.query && req.query.token) {
      return req.query.token;
    }
    return null;
  }
}).unless({
  path: tokenNotRequiredWhenMatch
}));

app.post('/test', (req, res) => {
  console.log(111);
  console.log(req.cookies); // Here I can get the values in the cookies!!!
});

Like I explained in the above code, before the request actually hit the url handler, that is in the ahead middleware, I cannot get the cookies, but when the request actually hit the url handler, then I can get it, how to solve this?



via lnshi

No comments:

Post a Comment