Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 308
Matthew Scragg Avatar asked Dec 05 '22 16:12

Matthew Scragg


1 Answers

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.

like image 154
Matt Ball Avatar answered Jan 14 '23 22:01

Matt Ball