2012-09-24 29 views
6

我在express3.0rc2上。如何使用app.locals.use(它还存在)和res.locals.useexpress 3.0如何使用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();}) 

,然后在任何航线调用这个中间件

感谢

回答

8

如果我理解正确的话,你可以做到以下几点:

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.custom变量。确保你在路由器之前放置了app.use功能!

编辑:

确定下试试:)您可以使用您的中间件和路由指定它你想要的:

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(); 
}); 
+0

不,我想调用不同路线的功能,我假设app.locals会帮助我做 – coool

+0

编辑我的回答 – zemirco

+0

谢谢。但是如果您检查了我发送的github链接,则定义了myMiddleware,然后从现在的路由函数调用app.locals.use(myMiddleware)可以调用myMiddleware。但我无法这样做,因为app.locals.use引发错误。什么是res.locals.use(我明白res.locals)的概念..再次感谢 – coool

10

我使用的是Express 3.0,这适用于我:

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

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

+1

我明白res.locals,但最新的res.locals.use .. ?? – coool

+0

'res.locals'仅用于将值传递给模板。 'res.locals.use'是未定义的,除非您指定它。看看https://github.com/visionmedia/express/blob/master/lib/response.js#L708 –

+1

我对这句话感到困惑:“然后我可以访问** myVal **和** myOtherVal * *“,因为我认为这意味着你可以像'myVar + ='anotherString''那样做,但是你仍然必须拥有** res.locals。**部分,即'res.locals.myVar + =' anotherString''。那么它会工作 –