![](/img/trans.png)
[英]Parsing JSON response as a variable to handlebars view in node.js / express
[英]Passing a controller variable to a view in Express/Node.js
第一种方法
res.render('index',{people:people});
第二种方法
res.locals.people = people;
res.render('index');
我看到有两种传递变量以查看的方法,上述方法有什么不同?
我认为传递变量来渲染模板是相同的,但是有区别。 您可以使用res.locals
从serval中间件传递变量。
res.locals
包含响应局部变量的对象,该局部变量的范围仅限于该请求,因此仅可用于在该请求/响应周期(如果有)中呈现的视图。 否则,此属性与app.locals相同。
此属性对于公开请求级别的信息很有用,例如请求路径名,经过身份验证的用户,用户设置等。
app.use(function(req, res, next){
res.locals.user = req.user;
res.locals.authenticated = ! req.user.anonymous;
next();
});
通过此代码,您可以将req.user
传递给下一个中间件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.