Kossel Kossel - 3 months ago 11
Node.js Question

Where should I put routes in express.js

I just started to learn node.js with express 4. I have read some books and tutorials, I also cloned some sample apps from git but I still have a very basic question, which practice should I follow to write the routing(or controller)?

Some people define all the routes in app.js, and export all the functions in the controller:

app.js

....
var homeController = require('./controllers/home');
var userController = require('./controllers/user');
....
app.get('/', homeController.index);
app.get('/login', userController.getLogin);
app.get('/logout', userController.logOUT);
app.get('/doStuff', userController.doStuff);


then in controllers/user.js

exports.getLogin = function(req, res) {
//logic...
});
exports.logout = function(req, res) {
//logic...
});
exports.doStuff = function(req, res) {
//logic...
});


Another way is like express-generator way:
app.js

...
app.use('/users', users);
...


controllers/users.js

....
router.get('/login', function(req, res, next) {
//logic...
});
router.get('/logout', function(req, res, next) {
//logic...
});
router.get('/doStuff', function(req, res, next) {
//logic...
});

module.exports = router;


And other are more dynamic like this proposal

is there any technical difference? Which pattern should I follow?

Answer

This is completely preferential. Any pattern that works is likely to be valid here. Express routers make things very nice and easy to setup. Personally I prefer to create a directory for every top level route, files for the second level, and exports for the third. Here's an example of how I lay things out for a set of API routes.

Directory:

routes/
  index.js <- master route manifest
  api/
    index.js <- api routes manifest
    books.js
    authors.js
  landing-pages/
    index.js
    awesome-deal.js

Route manifest:

// routes/index.js
var router = require('express').Router();
router.use('/api', require('./api'));
router.use('/landing', require('./landing-pages'));
module.exports = router;

API routes manifest:

// routes/api/index.js
var router = require('express').Router();
router.use('/books', require('./books.js'));
router.use('/authors', require('./authors.js'));
module.exports = router;

Entity endpoints:

// routes/api/books.js
var router = require('express').Router();
var db = require('mongoose-simpledb').db;
router.get('/get/:id', function (req, res) {
  var id = req.param('id');
  db.Book.findOneById(id, function (err, book) {
    if (err) throw err;
    res.json(book);
  });
});
router.post('/new', /* etc... */);
return router;

Then in my app file I only setup the the top-level route:

// app.js
/* express setup.... */
app.use('/', require('./routes'));