我在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();}) 然后在任何情况下都可以称之为这个中间件
谢谢
发布于 2012-09-25 03:39:11
我使用的是Express 3.0,这对我来说很有效:
app.use(function(req, res, next) {
res.locals.myVar = 'myVal';
res.locals.myOtherVar = 'myOtherVal';
next();
});然后我可以在我的模板中访问myVal和myOtherVal (或者直接通过res.locals)。
发布于 2012-09-25 03:23:46
如果我理解正确的话,您可以执行以下操作:
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函数放在路由器之前!
编辑:
ok next try :)您可以使用您的中间件并在您想要的路由中指定它:
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();
});https://stackoverflow.com/questions/12570923
复制相似问题