【问题标题】:using middlewares for specific namespaces in restify在 restify 中为特定命名空间使用中间件
【发布时间】:2014-12-17 05:47:49
【问题描述】:

我想使用中间件来检查某些路由的用户凭据(那些以/user/ 开头的路由),但令我惊讶的是server.use 没有将路由作为第一个参数并且使用restify-namespace @987654324 @ 效果仍然是全局的。

有没有比将我的身份验证中间件传递给控制器​​旁边的所有路由更好的方法?

【问题讨论】:

    标签: node.js namespaces restify


    【解决方案1】:

    我想我将只使用server.use 并在中间件内部进行以下路由检查:

    if (req.url.indexOf('/user/') !== 0) {
        return next();
    }
    

    【讨论】:

      【解决方案2】:

      不幸的是,restify 似乎不像 express,它支持 * 运算符。因此,我建议将您想要的路线组合在一起并在它们之前应用.use

      即:

      server.get('/test', function(req, res, next) {
        // no magic here. server.use hasn't been called yet.
      });
      
      server.use(function(req, res, next) {
        // do your magic here
        if(some condition) {
          // magic worked!
          next(); // call to move on to the next middleware.
        } else {
          // crap magic failed return error perhaps?
          next(new Error('some error')); // to let the error handler handle it. 
        } 
      });
      
      server.get('/admin/', function(req, res, next) {
        // magic has to be performed prior to getting here!
      });
      
      server.get('/admin/users', function(req, res, next) {
        // magic has to be performed prior to getting here!
      });
      

      但是,我个人主张使用express,但请选择适合您需要的任何内容。

      【讨论】:

        猜你喜欢
        • 2012-01-20
        • 1970-01-01
        • 2011-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-26
        • 2020-02-19
        相关资源
        最近更新 更多