coool
coool

Reputation: 8297

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

Upvotes: 7

Views: 15627

Answers (2)

zemirco
zemirco

Reputation: 16395

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

Upvotes: 9

Casey Foster
Casey Foster

Reputation: 6010

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

Upvotes: 11

Related Questions