How to mount express.js sub-apps over uri with parameter

1.8k Views Asked by At

I'd like to be able to mount a whole express sub-app on a uri containing a parameter. I've something similar to the following:

in app.js:

var app_authors = require('./api/authors');
var app = express();
...
app.use('/api/authors', app_authors);
...
module.exports = app;

in api/authors.js:

var app_author_books = require('./api/books');
var app = express();
...
app.get('/:author', ...);
...
app.use('/:author/books', app_author_books);
...
module.exports = app;

While the first sub-app works, mounted over /api/authors, the nested one doesn't (urls of the form /api/authors/:author/books and similar are not recognized)

EDIT:

For the curious, AFAIK sub-apps are not very clearly documented, but they should work, at least according to TJ Holowaychuk's Modular web applications with Node.js and Express (and the related vimeo screencast). See also this other SO answer.

2

There are 2 best solutions below

2
On

It seems that you want to create different "applications" to separate the routes/services in different files.

You should try the approach given here in which they pass the app variable as a parameter, and hence, you only have one application that controls all the routes (that are located in your separate files).

I hope this is what you're looking for.

1
On

In Express 4, when you mount a sub-app on a path (or a regex), this path is removed from req.path (but is still in req.originalUrl).

See this github issue and Express 4 doc about mountpoints.