Skip to content

Express response.locals

TIP

使用此属性设置在使用 res.render 呈现的模板中可访问的变量

Express
res.locals

使用此属性设置在使用 res.render 呈现的模板中可访问的变量。res.locals 上设置的变量在单个请求-响应周期内可用,并且不会在请求之间共享。

为了保留局部变量以用于请求之间的模板渲染,请改用 app.locals。

此属性对于向应用程序中呈现的模板公开请求级信息(例如请求路径名称、经过身份验证的用户、用户设置等)很有用。 设置响应头字段field 值为 value, 也可以一次传入一个对象设置多个值。

Express
app.use((req, res, next) => {
  // Make `user` and `authenticated` available in templates
  res.locals.user = req.user
  res.locals.authenticated = !req.user.anonymous
  next()
})