I'm trying to find the best method to separate routes in Express. I'm aware of two methods and I was wondering what the difference is between them, and which one is considered 'best practice' (and why).
Method one - exports
Lots of examples seem to use this method
app.js
var user = require('./routes/users');
app.get('/users', user.list);
routes/users.js
exports.list = function(req, res){
res.render('users', { title: 'Users', users: users });
};
Method two -
This method is used in the express guide
app.js
var users = require('./routes/users');
app.use('/users', users);
routes/users.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res){
res.render('users', { title: 'Users', users: users });
});
module.exports = router;
So as I said above, which one is the preferred method, and why?
Method three - use both
You should be taking advantage of both the router introduced in Express 4 and the modularization of your controllers.
app.js
var routes= require('./routes');
app.use('/', routes);
routes/index.js
var express = require('express');
var users = require('../routes/users');
var router = express.Router();
router.use('/users', users);
module.exports = router;
routes/users.js
var express = require('express');
var users = require('../controllers/users');
var router = express.Router();
router.get('/', users.list);
module.exports = router;
controllers/users.js
exports.list = function(req, res){
res.render('users', { title: 'Users', users: users });
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With