I am kinda new to express.js and did not find a matching answer to my problem yet.
I've got an express app with a folder structure like this:
app/
|--app.js
|--routes/
|--|--index.js
|--|--news.js
|--|--users.js
|--some_other_folders/
As for now, I've got my routes managed in the app.js, like this:
var index = require('./routes/index');
var users = require('./routes/users');
...
app.use('/', index);
app.use('/users', users);
...
This works fine, but I originally wanted to manage all my routes with only one file, so that I only need to reference this file in the app.js.
Something like this:
[app.js]
var routes = require('./routes/routes');
app.use('/', routes);
[routes/routes.js]
...
router.get('/', function(req, res) {
res.render('index.html');
});
require('./users'); // This is meant to refer to the users routes
...
Is there a way to include my other route files (like users, news, ...) into the "main"-route file?
Or are there maybe other best-practices to mange routes within express.js?
Thank you so much for your help!
Yes, there are good way to do this
[app.js]
var routes = require('./routes/routes')(app);
[routes/routes.js]
var user = require('./user'); // get user controllers
module.exports = function(app) {
app.get('/', function() { ... });
app.get('/another-path', function() { ... });
app.get('/user/:id', user.display);
app.post('/user/:id', user.update);
};
[routes/user.js]
module.exports.display = function(req, res) {
...
res.render('user', data);
}
module.exports.update = function(req, res) {
...
res.render('user', data);
}