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.
function a(req, res, next){
req.data = data;
next();
};
app.get('/*', a);
See the example at the bottom of the Express docs, Middleware section.
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.
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.