我正在尝试在我目前正在从事的项目中使用 JWT token 。我正在尝试使用中间件在将 JWT token 传递给下一个处理程序之前验证它。但是,我有一个奇怪的问题,我没有在中间件中获得 JWT token ,但是如果我将它传递给下一个处理程序,我将获得 token 。希望下面的例子能解释它:
我已经实现了一个 PING 方法和一些日志记录来向您展示发生了什么。我的设置如下所示:
this._express.use((req, res, next) => {
console.log('AUTH');
return jwt.verify(req.headers['x-access-token'], 'mysecret', (err, decoded) => {
if (err) {
console.log(`ERROR: ${err}`);
return false;
}
console.log('DECODED');
return next();
});
});
//Health Check
this._express.get('/ping', (req, res) => {
console.log(`PING`);
return res.status(200).send('pong');
});
如果我执行这段代码,输出是:
node_1 | AUTH
node_1 | ERROR: JsonWebTokenError: jwt must be provided
但是,如果我在中间件中使用 next() 回调:
this._express.use((req, res, next) => {
console.log('AUTH');
next(); // This is the only thing that is different
return jwt.verify(req.headers['x-access-token'], 'mysecret', (err, decoded) => {
if (err) {
console.log(`ERROR: ${err}`);
return false;
}
console.log('DECODED');
return next();
});
});
//Health Check
this._express.get('/ping', (req, res) => {
console.log(`PING`);
return res.status(200).send('pong');
});
输出如下:
node_1 | AUTH
node_1 | ERROR: JsonWebTokenError: jwt must be provided
node_1 | AUTH
node_1 | PING
node_1 | DECODED
我对 JWT token 没有太多经验,如果有什么明显的地方请原谅。
最佳答案
所以我设法找到了问题所在。问题在于 CORS。特别是,中间件按预期工作,但是由于 CORS,发送的预检请求没有 JWT token ,这就是我在第一个示例中收到错误的原因。我已经更新了中间件以跳过预检请求:
if (req.headers['access-control-request-headers'] === 'x-access-token') {
return next();
}
[...]
关于node.js - 无法在中间件中获取 JWT token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53278551/