有没有一种方法可以通过中间件将jwt应用到我的所有快速路由上,而不是在令牌丢失或无效时引发错误,而是使用null
填充req.user
我目前的解决方案是:
var jwt = require('express-jwt');
var router = express.Router();
router.use(jwt({ secret: 'secret'}));
///////////////////////////////////////////
// This is the piece I would like to avoid
router.use((err, req, res, next) => {
if (err.code === 'UnauthorizedError') {
req.user = null;
}
next();
})
///////////////////////////////////////////
router.use('/products', require('./products/products_router'));
在我的路由中,如果token缺失或无效,我希望使用req.user === null
,如果token有效,则使用正确的req.user
。目前,如果没有我想要删除的代码,没有令牌就不会执行我的路由。如果我使用unless()
,则即使使用有效的令牌也不会填充req.user
发布于 2018-09-10 08:47:50
根据documentation,您可以在options对象中指定"credentialsRequired“属性:
app.use(jwt({
credentialsRequired: false
}));
您可以在原始源代码中看到这是如何工作的:
if (!token) {
if (credentialsRequired) {
return next(new UnauthorizedError('credentials_required', { message: 'No authorization token was found' }));
} else {
return next();
}
}
https://stackoverflow.com/questions/52249505
复制相似问题