我在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();})
Run Code Online (Sandbox Code Playgroud)
然后在任何路由中调用此中间件
谢谢
Cas*_*ter 10
我正在使用Express 3.0,这对我有用:
app.use(function(req, res, next) {
res.locals.myVar = 'myVal';
res.locals.myOtherVar = 'myOtherVal';
next();
});
Run Code Online (Sandbox Code Playgroud)
然后,我有访问myVal,并myOtherVal在我的模板(或直接通过res.locals).
如果我理解正确,您可以执行以下操作:
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)
});
Run Code Online (Sandbox Code Playgroud)
您现在可以在每个路由中使用req.custom变量.确保将app.use功能放在路由器之前!
编辑:
好的下一次尝试:)你可以使用你的中间件并在你想要的路线中指定它:
function myMiddleware(req, res, next) {
res.locals.uname = 'fresh';
next();
}
app.get("/", myMiddleware, function(req, res) {
res.send(req.custom)
});
Run Code Online (Sandbox Code Playgroud)
或者你可以"全局"设置它:
app.locals.uname = 'fresh';
// which is short for
app.use(function(req, res, next){
res.locals.uname = "fresh";
next();
});
Run Code Online (Sandbox Code Playgroud)