我可以在模板中直接使用app.locals,但不能使用res.locals

4
在我的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

可能是重复的问题:ExpressJS 3.0 如何传递 res.locals 到 jade 视图? - Robert Moskal
@RobertMoskal 不对。app.router 在4.x版本中已经被废弃了。 - David Jones
2个回答

8

res.localsres.render 中可用。我怀疑你误调用了 app.render,应该调用 res.render


就是这样!我没有意识到使用app.renderres.render之间存在差别。 - David Jones

0

只要应用程序在运行,app.locals 就可以在整个应用程序中使用。而 res.locals 只在请求期间存在。


正确,这就是为什么我将它们设置在中间件中的原因。 - David Jones

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接