Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express 3.0 how to use app.locals.use and res.locals.use

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

like image 755
coool Avatar asked Sep 24 '12 18:09

coool


2 Answers

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).

like image 145
Casey Foster Avatar answered Nov 09 '22 15:11

Casey Foster


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();
});
like image 20
zemirco Avatar answered Nov 09 '22 16:11

zemirco