How to mount app.get() routes on a particular path prefix How to mount app.get() routes on a particular path prefix express express

How to mount app.get() routes on a particular path prefix


With Express 4.0, the task is much cleaner with the Router. You can create as many routers as you need to nicely partition your app, and then attached them with app.use(). For example:

myapp.js

var express = require("express"),    router  = express.Router(),    app     = express(),    port    = 4000;// Here we declare our API which will be visible under prefix pathrouter.get('/', function (req, res) {    console.log("request to subspace hello");    res.send({ message: "Hi from subspace /api/v1/"});});// we attach our routes under /api/v1app.use('/api/v1', router);// here we have direct, root-level routingapp.get('/', function (req, res) {    console.log("request to rootspace hello");    res.send({message: "Hi from root /"});});app.listen(port);console.log("App active on localhost:" + port);

Then run

node myapp.js

and visit

http://localhost:4000 and http://localhost:4000/api/v1


Here's a working example of mounting a route in Express 3:

./snipe3app.js

var express = require('express');var app = module.exports = express();app.get('/subapp', function (req, res) {  res.send('You are on the /sub/subapp page.');});

./app.js

var express = require('express'),    http = require('http'),    subApp = require('./snipe3app'),    app = express();app.use(express.favicon());app.use(express.bodyParser());app.use(app.router);app.use('/sub', subApp);app.get('/', function (req, res) {  res.send('You are on the root page');});http.createServer(app).listen(3000, function(){  console.log('Express server listening on port 3000. Point browser to route /secure');});

You have to pay attention to the order in which the routes are handled when doing this.