Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express - Route separation methods

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?

like image 484
Ash Avatar asked Apr 22 '15 11:04

Ash


1 Answers

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 });
};
like image 174
Ben Fortune Avatar answered Oct 06 '22 01:10

Ben Fortune