1 thought on “base url

  1. Yes, express 4.x router makes it easy to mount ‘mini-apps’ on base-urls.

    e.g. if you want to define a base url as /foo and then mount a bunch of routes /bar, /bar/:barId onto it so that the full paths would be /foo/bar, /foo/bar/:barId respectively, you will do the following:

    var express = require('express');
    var app = express();
    var router = express.Router();
    
    // this will only be invoked if the path ends in /bar
    router
    .route('/bar')
    .all(function(req, res, next) {
      // middleware logic here for all verbs (get, put, post, delete)
      next();
    })
    .get(function(req, res, next) { 
      // invoked on get /foo/bar
      res.send('Hello world!');
    });
    
    router
    .route('/bar/:barId')
    .put(function(req, res, next) {
      // invoked on put /foo/bar/:barId
      res.send(req.params.barId);
    });
    
    // mount the '/bar' router on to the '/foo' base url
    app.use('/foo', router);
    
    app.listen(3000);

    Modified example from : http://expressjs.com/4x/api.html#router

Comments are closed.