【问题标题】:How to decorate app methods in express?如何在 express 中装饰应用程序方法?
【发布时间】:2015-07-10 01:56:30
【问题描述】:

我使用 node.js 并表达 v4.12。我想通过自定义逻辑来装饰所有app.get 调用。

app.get(/*getPath*/, function (req, res, next) {
    // regular logic
});

和我的自定义逻辑

customFunc() {
 if (getPath === 'somePath' && req.headers.authorization === 'encoded user'){
       //costum logic goes here
       next();
    } else {
       res.sendStatus(403);
    }     
}

这个想法是在我已经拥有的代码之前执行自定义逻辑,但我需要在我的自定义函数中访问reqresnext 对象。另一个问题是我需要 app.get 参数才能在 custumFunc 中使用请求的模式。 我尝试像这样实现装饰器模式:

var testfunc = function() {
    console.log('decorated!');
};

var decorator = function(f, app_get) {
    f();
    return app_get.apply(this, arguments);
};
app.get = decorator(testfunc, app.get);

但是 javascript 会抛出一个错误。

编辑 如果app.use() 我只能获得像/users/22 这样的req.path,但是当我像app.get('/users/:id', acl, cb) 一样使用它时,我可以获得req.route.path 属性,它等于'/users/:id',这就是我的ACL 装饰器所需要的。但我不想为每个端点调用 acl 函数并尝试将其移动到 app.use() 但 req.route.path 属性。

【问题讨论】:

  • 它会抛出什么错误?
  • 有lazyloader错误

标签: javascript node.js express decorator


【解决方案1】:

您正在尝试构建middleware。只需通过 app.use 将您的装饰器添加到应用程序。

【讨论】:

    【解决方案2】:

    实现你的middleware的例子:

    app.use(function(req, res, next) {
     if (req.path==='somePath' && req.headers.authorization ==='encoded user'){
           //costum logic goes here
           next();
        } else {
           res.sendStatus(403);
        }  
    });
    

    如果你只想在一个路由中传递中间件,你可以这样实现:

    app.get(/*getPath*/, customFunc, function (req, res, next) {
        // regular logic
    });
    

    【讨论】:

    • 有问题。当我使用 app.use() 时,我只能获得 req.path 属性,例如 '/users/22' 但是当我像 app.get('/users/:id', acl, cb) 那样使用它时,我可以获得 req。 route.path 等于'/users/:id',这个属性是我需要为我的 ACL 装饰器提取的。如果 app.use() 我需要解决当前请求使用的模式。
    • 如果我想将它用于所有路由并且我需要 req.route.path 属性,我该怎么办? (不是 req.path)
    猜你喜欢
    • 2016-03-23
    • 2010-11-24
    • 2016-06-04
    • 2019-02-03
    相关资源
    最近更新 更多