有没有一种方便的方法可以在 Express 中分几步装饰视图选项?
我有一些将在每个动态页面上使用的变量,就像在布局中使用的一样。我们称它们为用户
和城市
。对于 user
我按照明确的指令将中间件放在我使用它的位置前面,除了我这样做:
app.get('/*', function(req, res, next){
req.user = { name: "Kit" };
next();
});
将 user
放在 上似乎是有意义的>req
,但它在 cities
上有点崩溃,因为它似乎在语义上不适合 req 对象:
app.get('/*', function(req, res, next){
User.collection.distinct('city', function(err, response){
req.cities = response;
next();
});
req.menu = response;
});
然后我遵循:
app.get('/:city', function(req, res){
res.render('city', { cities: cities, user: user });
});
是否有更好的方法这?
I have some variables that will be used on every dynamic page, as it's used in the layout. Lets call them user
and cities
. For user
I followed the express instruction to put a middleware infront of where I'd use it, except I did this:
app.get('/*', function(req, res, next){
req.user = { name: "Kit" };
next();
});
It seem to make sense to put user
on req
, but it breaks down a bit on cities
as it doesn't seem to semantically fit on the req object:
app.get('/*', function(req, res, next){
User.collection.distinct('city', function(err, response){
req.cities = response;
next();
});
req.menu = response;
});
Which I then follow by:
app.get('/:city', function(req, res){
res.render('city', { cities: cities, user: user });
});
Is there a better way of going about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为你的做法有什么严重的错误,特别是对于一个小的代码库。看起来城市与用户绑定在一起,因此您可能只想通过在
User.collection 中执行
req.user.cities = response
将城市挂在 req.user 上。不同的回调。另一件事是您在每次请求时都会查询这些城市。这可能没问题,但如果该数据相对静态,则使用会话并在会话生命周期内缓存该数据作为优化是有意义的。如果您只想有一个更清晰的名称,您可以创建一个顶级
locals
对象,挂起该请求,然后挂起用户和城市,以便req.locals.cities
。I don't see anything horribly wrong with how you're doing it, especially for a small code base. It looks like the cities are tied to the user, so you might just want to hang the cities off of req.user by doing
req.user.cities = response
in yourUser.collection.distinct
callback. The other thing is that you are querying for these cities on every request. This might be fine, but if that data is relatively static, using sessions and caching that data during the session lifetime would make sense as an optimization.If you want to just have a clearer name, you can make a top level
locals
object, hang that off request, and then hang both user and cities off of that soreq.locals.cities
.