express Routing Multiple Routes


Example

The main app file loads any routes files in which you would like to define routes. To do so we need the following directory structure: app.js routes/index.js routes/users.js

app.js

var express = require('express');
var app = express();

app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'))

app.listen('3000');

routes/index.js

var router = require('express').Router();

router.get('/', function(req, res) {
    res.send('Index Page');
});

router.get('/about', function(req, res) {
    res.send('About Page');
});

module.exports = router;

routes/users.js

var router = require('express').Router();

router.get('/', function(req, res) {
    res.send('Users Index Page');
});

router.get('/list', function(req, res) {
    res.send('Users List Page');
});

module.exports = router;

Running $ node app.js there should now be pages at the following urls:

  • localhost:3000/ - Displays "Index Page"
  • localhost:3000/about - Displays "About Page"
  • localhost:3000/users - Displays "Users Index Page"
  • localhost:3000/users/list - Displays "Users List Page"