如何在快递中装饰应用程序方法



我使用 node.js 和 express 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属性。

实现中间件的示例:

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 将您的装饰器添加到应用程序中即可。

最新更新