How to export all routes in Express?
What I do is group my routes by controller. For each group of related routes (users, shopping cart, whatever), I make a controller file that lives in app/controllers/foo.js
where foo
is the controller name. In my main javascript server file (where all your code currently lives), I require
each controller by name and then call its setup
function, passing in my express app
object, and allow the controller to add whatever routes it needs.
['api', 'authorization', 'users', 'tests'].map(function(controllerName) {
var controller = require('./controllers/' + controllerName);
controller.setup(app);
});
Inside each controller, I do something like:
exports.setup = function(app) {
app.get('/dashboard', function(req, res) {
res.render('dashboard', {
username: req.session.username
});
});
};
Why not do something like this:
// logout.js
module.exports = function(req, res){
res.render('logout', {
username: req.session.username
});
});
// dashboard.js
module.exports = function(req, res){
res.render('dashboard', {
username: req.session.username
});
});
// login.js
module.exports = function(req, res){
res.render('login', {
badLogin: false,
loginError: false
});
});
// app.js
app.get('/logout', require('logout'));
app.get('/dashboard', require('dashboard'));
app.get('/login', require('login'));
Also, you could imagine easily using http://nodejs.org/docs/v0.4.8/api/fs.html#fs.readdir to loop through a routes directory and load these up programmatically.
You could even do something along the lines of...
module.exports.handler[] = {
method : 'get',
route : '/login',
action : res.render('login', {
badLogin: false,
loginError: false
});
}
Though I think I'd spend a little time thinking about how to simplify that.