Node.js 我可以在模板中直接使用app.locals,但不能在res.locals中使用
在我的Express应用程序中,我可以设置Node.js 我可以在模板中直接使用app.locals,但不能在res.locals中使用,node.js,express,Node.js,Express,在我的Express应用程序中,我可以设置app.locals,并在模板中直接使用它们(使用渲染)。但是,当我在中间件中设置res.locals时,它们不可用,除非我传入它们。我做错什么了吗 服务器 app.locals.foo = "foo"; app.use(function(req, res, next) { res.locals.bar = "bar"; next(); }); 模板 {{foo}} {{bar}} 测试1 app.get("/", function(req,
app.locals
,并在模板中直接使用它们(使用渲染)。但是,当我在中间件中设置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);
});
});
结果
测试2
app.get("/", function(req, res) {
app.render("template.html", {bar: res.locals.bar}, function(error, html) {
res.send(html);
});
});
结果
只要应用程序启动,app.locals就可以在整个应用程序中使用。res.locals仅在请求期间存在
res.locals
在res.render
中提供。我怀疑您错误地调用了app.render
,并且应该调用res.render
正确,这就是我在中间件中设置它们的原因。可能重复@RobertMoskal Nope<代码>应用程序路由器在4.x中被弃用。就是这样!我没有意识到使用app.render
和res.render
之间有区别。
app.get("/", function(req, res) {
app.render("template.html", {bar: res.locals.bar}, function(error, html) {
res.send(html);
});
});
foo bar