如何在 express 中装饰应用程序方法?

How to decorate app methods in express?

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

您正在尝试构建 middleware。只需通过 app.use.

将装饰器添加到应用程序

实施您的 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
});