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

Dav*_*nes 4 node.js express

在我的Express应用程序中,我可以app.locals直接在我的模板中设置和使用它们(使用快速手柄渲染).但是,当我设置res.locals中间件时,除非我将它们传入,否则它们不可用.我做错了什么?

服务器

app.locals.foo = "foo";
app.use(function(req, res, next) {
  res.locals.bar = "bar";
  next();
});
Run Code Online (Sandbox Code Playgroud)

模板

{{foo}} {{bar}}
Run Code Online (Sandbox Code Playgroud)

测试1

app.get("/", function(req, res) {
  app.render("template.html", {}, function(error, html) {
    res.send(html);
  });
});
Run Code Online (Sandbox Code Playgroud)

结果

foo
Run Code Online (Sandbox Code Playgroud)

测试2

app.get("/", function(req, res) {
  app.render("template.html", {bar: res.locals.bar}, function(error, html) {
    res.send(html);
  });
});
Run Code Online (Sandbox Code Playgroud)

结果

foo bar
Run Code Online (Sandbox Code Playgroud)

bol*_*lav 8

res.locals可用res.render.我怀疑你是app.render在误叫,应该打电话res.render.