0

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.

Adam
  • 482
  • 4
  • 15
  • 1
    Definitely not ans answer to your question, but your current code could be made shorter and safer with `users[req.params.name]` instead of your `eval` statement. – apsillers Aug 01 '13 at 19:05

3 Answers3

1
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');
});
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
0

You might want to check this earlier answer on stackoverflow - https://stackoverflow.com/a/6064205/821720

A little more code but abstracts routing to the next level and also gives you a cleaner main file.

Community
  • 1
  • 1
Mukesh Soni
  • 6,646
  • 3
  • 30
  • 37
0

I have been working on something like this, focused on REST routes. Take a look at https://github.com/deitch/booster

If your routes are RESTful:

var booster = require('booster'), express = require('express'), app = express(), db = require('./myDbSetup');

booster.init({app:app,db:db});
booster.resource('user');

app.listen(3000);

You just need to wire up the database/persistence connection layer. You can choose to customize the controller routes, or the models, or any part of it, but all optional.

deitch
  • 14,019
  • 14
  • 68
  • 96