MattDionis MattDionis -5 years ago 148
Node.js Question

How to correctly use Express 4 multiple routers

I'm attempting to use the Express 4 Router to use a different router based on the path. I want all

routes handled by
, and every other route handled by
. The below setup serves me all the
routes correctly, but seems to ignore
as I get a 'Cannot GET...' message each time I test those endpoints.


var version1 = require('./routes/vers1');
var version2 = require('./routes/vers2');

module.exports = function(app) {

app.all('/api/v2/*', version2);

app.all('/*', version1);


Answer Source

Method routes (.get, .post, and of course .all) are terminal. This is why you can use wildcards with them as well. .use is not terminal and doesn't allow wildcards -- it acts as a prefix. This is an implementation choice of express. Use .use without wildcards.

The fact that app.use("/*", version1) works is purely incidental. This will match any route and fall through to version1[method](path). Since there is no prefix to strip, if the request route matches path, express will consider this a match and serve that route.

Use .use.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download