【发布时间】: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);
}
}
这个想法是在我已经拥有的代码之前执行自定义逻辑,但我需要在我的自定义函数中访问req、res 和next 对象。另一个问题是我需要 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