08-02-2023, 04:43 PM
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 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?