ExpresJS:app.get()/ app.set()数据生存期

在express.js中,我们可以使用app.set / get来获取请求中的variables,将它们打印在玉石视图中,并在高级中间件中访问它们。

但是 – 在express的文档中找不到这些variables的生命周期。

例如,如果我使用:

app.set('my-var', 'here is my var'); 

并试图把它放在同一个中间件链中:

 console.log(app.get('my-var')); // would work 

但是在一个新的请求中间件链上,我得到了undefined

我可以通关吗?

只要没有人不会覆盖它,请从express/lib/application.js

app.init() – bootsrapp ExpressJS

 this.settings = {}; 

默认configuration – 将设置分配给当地人

 this.locals.settings = this.settings; 

app.set() – 方法定义

 app.set = function(setting, val){ // set value this.settings[setting] = val; 

app.render() – 是时候渲染视图

 app.render = function(name, options, fn){ var opts = {}; var view; // merge app.locals merge(opts, this.locals); // merge options._locals if (options._locals) { merge(opts, options._locals); } // merge options merge(opts, options); // render try { view.render(opts, fn); } catch (err) { fn(err); } } 

ExpressJS中没有什么魔法 – 设置和local.settings在渲染之前被合并。 没有方法 – 清除设置,清除当地人。 无论设置什么,它都是可行的。