【发布时间】:2016-06-03 03:34:45
【问题描述】:
在我的 Express 应用程序中,我可以设置 app.locals 并直接在我的模板中使用它们(使用 express-handlebars 渲染)。但是,当我在中间件中设置res.locals 时,除非我传入它们,否则它们不可用。我做错了什么吗?
服务器
app.locals.foo = "foo";
app.use(function(req, res, next) {
res.locals.bar = "bar";
next();
});
模板
{{foo}} {{bar}}
测试 1
app.get("/", function(req, res) {
app.render("template.html", {}, function(error, html) {
res.send(html);
});
});
结果
foo
测试 2
app.get("/", function(req, res) {
app.render("template.html", {bar: res.locals.bar}, function(error, html) {
res.send(html);
});
});
结果
foo bar
【问题讨论】:
-
@RobertMoskal 不。
app.router在 4.x 中已弃用。