Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Is it possible to automate routing in Express?

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.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Is it possible to automate routing in Express?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×