Matthew Scragg
Matthew Scragg

Reputation: 4638

Nodejs Express implicit middleware applied to all routes?

I wanted to know if Express would let me create a route middleware that would be called by default without me explicitly placing it on the app.get() arg list?

// NodeJS newb

var data = { title: 'blah' };

// So I want to include this in every route
function a(){
  return function(req, res){
    req.data = data;
  };
};

app.get('/', function(req, res) {
  res.render('index', { title: req.data.title });
};

I understand I can do app.set('data', data) and access it via req.app.settings.data in the route. Which would probably satisfy my simple example above.

Upvotes: 4

Views: 9014

Answers (3)

Matt Ball
Matt Ball

Reputation: 359776

function a(req, res, next){
  req.data = data;
  // Update: based on latest version of express, better use this
  res.locals.data = data;
  next();
};

app.get('/*', a);

See the examples on the Express docs, Middleware section.

Upvotes: 11

Ito
Ito

Reputation: 2167

You can create a default way to call every view you have made without have to explicit create a new route for every new entry. Check out this following example:

app.get('/:viewname', function(req, res) {
    res.render(req.params.viewname, { viewname : req.params.viewname});
});

I hope it's you're looking forward.

Upvotes: 4

esp
esp

Reputation: 7677

You can also do it this way:

function my_middleware(req, res, next){
   req.data = data;

   if (something(res)) redirect('http://google.com'); // no access to your site
   next(); // go to routes

};

app.configure(function() {
   ...
   app.use(express.cookieParser('secret'));
   app.use(express.session());
   app.use(my_middleware);
   app.use(app.router);
   ...
}

In this case my_middleware is called when cookies and sessions are already available, but no routes are processed yet. Or you can even do it before session if you need it for some reason.

Upvotes: 1

Related Questions