res.locals是干嘛用的

一般用来把req的一些参数传递回res,这样做方便网页显示上次请求的一些信息

也可以是给模板用的,一些模板里的常用变量不需要每次 render 时传入,比如在中间件里声明:res.locals.username = 'cnode', 然后在模板里就可以直接使用 <%= username %> 了。跟 koa 里的 state 一样:

locals的值和res.send回去的值一样,我设置locals={a:100},那么每个请求回去的数据都会都到这个值?

res.locals

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

app.use(function(req, res, next){
  res.locals.user = req.user;
  res.locals.authenticated = ! req.user.anonymous;
  next();
});
posted @ 2017-05-27 16:27  little_ab  阅读(2168)  评论(0编辑  收藏  举报