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
)访问myVal
和myOtherVal
。
如果我理解正确,你可以做以下的事情:
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(); });
- 快速错误 – TypeError:Router.use()需要中间件function,但有一个对象
- iisnode处理请求时遇到错误。 HTTP状态:500
- 在Node.js中设置一个cookie值
- Node.JS使用Sails.JS框架 – 护照:没有战略注册名称:Facebook
- socket.io + redis + expressjs集群 – 在expressjs请求中获取套接字对象
- 错误:在sailsJs中间件中发送后无法设置标题
- 如何处理与瓦格纳的快速路线callback
- 快递js 4 – 如何configuration没有app.configure?
- Node.js + Express + Handlebars.js +部分视图