Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating Express.js 2 to 3, specifically app.dynamicHelpers() to app.locals.use?

Updated Express.js from version 2 to 3, and the following call to app.dynamicHelpers({..}) broke as it is no longer present in V3:

app.dynamicHelpers({

    request: function(req){
      return req
    },
    ...etc.
});

There's a migration guide which says this:

  • app.dynamicHelpers() (use middleware + res.locals)

But I'm stumped how to do that. Is there a more concrete example of how to migrate that?

Related SO post: nodejs express 3.0

like image 807
prototype Avatar asked Jul 20 '12 13:07

prototype


3 Answers

I had the same problem with session.user and just fixed it by understanding that the app.use function needs to be IN the configure part, not where it was before.

Before:

app.configure();
app.dynamicHelpers({
  user: function(req, res) {
    return req.session.user;
  }
});

After:

app.configure(function(){
  //...
  app.use(function(req, res, next){
    res.locals.user = req.session.user;
    next();
  });
  //...
});

for Flash have a look at connect-flash

like image 117
nooitaf Avatar answered Dec 08 '22 07:12

nooitaf


The solution with 16 votes is correct but be sure to use the res.locals assignment before app.use(app.router); refer to this post https://stackoverflow.com/a/12597730/1132109

like image 43
D4tech Avatar answered Dec 08 '22 06:12

D4tech


Have a look at the examples folder at github. For example auth:

app.use(function(req, res, next){
  var err = req.session.error,
      msg = req.session.success;
  delete req.session.error;
  delete req.session.success;
  res.locals.message = '';
  if (err) res.locals.message = '<p class="msg error">' + err + '</p>';
  if (msg) res.locals.message = '<p class="msg success">' + msg + '</p>';
  next();
});

You can then use the variable "message" in your template.

like image 35
zemirco Avatar answered Dec 08 '22 05:12

zemirco