expression3.0如何使用app.locals.use和res.locals.use

我在express3.0rc2上。 如何使用app.locals.use (它仍然存在)和res.locals.use

我看到这个https://github.com/visionmedia/express/issues/1131,但app.locals.use引发错误。 我假设一旦我把这个函数放在app.locals.use中,我可以在路由中使用它。

我正在考虑添加

 app.locals.use(myMiddleware(req,res,next){res.locals.uname = 'fresh'; next();}) 

然后在任何路线上调用这个中间件

谢谢

我正在使用Express 3.0,这对我有用:

 app.use(function(req, res, next) { res.locals.myVar = 'myVal'; res.locals.myOtherVar = 'myOtherVal'; next(); }); 

然后我可以在我的模板(或直接通过res.locals )访问myValmyOtherVal

如果我理解正确,你可以做以下的事情:

 app.configure(function(){ // default express config app.use(function (req, res, next) { req.custom = "some content"; next(); }) app.use(app.router); }); app.get("/", function(req, res) { res.send(req.custom) }); 

您现在可以在每个路由中使用req.customvariables。 确保你把路由器之前的app.usefunction!

编辑:

确定下一个尝试:)你可以使用你的中间件,并在你想要的路线中指定它:

 function myMiddleware(req, res, next) { res.locals.uname = 'fresh'; next(); } app.get("/", myMiddleware, function(req, res) { res.send(req.custom) }); 

或者您可以将其设置为“全局”:

 app.locals.uname = 'fresh'; // which is short for app.use(function(req, res, next){ res.locals.uname = "fresh"; next(); });