代码之家  ›  专栏  ›  技术社区  ›  Carlo

在快速路线上应用jwt而不引起错误

  •  0
  • Carlo  · 技术社区  · 7 年前

    req.user 具有 null

    我当前的解决方案:

    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'));
    

    在我的路线上,我想 req.user === null 如果令牌有效。目前,如果没有我想要删除的代码,我的路由就不会在没有令牌的情况下执行。如果我使用 unless() ,的需求用户即使使用有效令牌也未填充

    1 回复  |  直到 7 年前
        1
  •  1
  •   user8021515 user8021515    7 年前

    根据 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();
      }
    }
    
    推荐文章