I am on express3.0rc2. How to use app.locals.use
(does it still exist) and res.locals.use
I saw this https://github.com/visionmedia/express/issues/1131 but app.locals.use throws an error. I am assuming that once I put the function in app.locals.use I can use it in the routes.
I was thinking of adding
app.locals.use(myMiddleware(req,res,next){res.locals.uname = 'fresh'; next();})
and then in any route call this middleware
thanks
I'm using Express 3.0 and this works for me:
app.use(function(req, res, next) {
res.locals.myVar = 'myVal';
res.locals.myOtherVar = 'myOtherVal';
next();
});
I then have access to myVal
and myOtherVal
in my templates (or directly via res.locals
).
If I understand you correctly you can do the following:
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)
});
You can now use the req.custom variable in every route. Make sure you put the app.use function before the router!
Edit:
ok next try :) you can either use your middleware and specify it in the routes you want:
function myMiddleware(req, res, next) {
res.locals.uname = 'fresh';
next();
}
app.get("/", myMiddleware, function(req, res) {
res.send(req.custom)
});
or you can set it "globally":
app.locals.uname = 'fresh';
// which is short for
app.use(function(req, res, next){
res.locals.uname = "fresh";
next();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With