Is it possible to automate routing in Express?
Problem
Is it possible to Automate Routing in Express, so I don't have to list out all the routes?
For example: going to URL '/users/first_example' should automatically use the "users.first_example" module.
app.get('/users/:name', function(req,res){
return eval('users.'+req.params.name); //failed attempt
});
There's got to be something I'm missing, and it would make my code look a lot more elegant.
Much appreciated.
Problem courtesy of: Adam
Solution
var users = require('./users');//a module of route handler functions
app.get('/users/:name', function(req,res){
var handler = users[req.params.name];
if (typeof handler === 'function') {
return handler(req, res);
}
res.status(404).render('not_found');
});
Solution courtesy of: Peter Lyons
Discussion
View additional discussion.