My app uses Node.js and Express 4 and has the following code in the app.js
file located in the root directory:
var express = require('express');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use('/', index);
app.use('/users', users);
The routes
folder in the root directory contains an index.js
file with the following code:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.render('index');
});
module.exports = router;
The routes
folder also contains a users.js
file with the following code:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.render('users');
});
module.exports = router;
I'm new to Express and Node.js. It's my understanding that this structure causes browser requests to domainName.com
to run the index.js
file, while requests to domainName.com/users
will run the users.js
file, resulting in different views being rendered in the browser.
What is the purpose of organizing the code this way? (i.e. why is app.use()
in app.js
used to isolate each router.get(path, callback)
into it's own respective module?)
Is the commonly-accepted practice to organize routes differently for a single page app versus a website consisting of mostly static text, such as a blog? If so, how?