Where should I put routes in express.js

I've just started learning node.js with expression 4. I've read several books and tutorials, I've also cloned some sample apps from git, but I still have a very simple question, what practice should I follow to write a routing (or controller)?

Some people define all routes in app.js and export all functions in a 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 similar to express generator mode: 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 others are more dynamic like this proposal

Is there a technical difference? Which model should you follow?

+3


source to share


1 answer


This is the completely preferred option. Any pattern that works is likely to be valid here. Express routers make things very nice and easy to set up. Personally, I prefer to create a directory for each top level route, files for the second level and export for the third. Here's an example of how I talk about the many API routes.

Catalog:

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

      

Route indicator:

// 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 application file, I only set the top level route:

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

      

+2


source







All Articles