Home > Enterprise >  Express subroute router, without having to use full path in each route
Express subroute router, without having to use full path in each route

Time:10-11

I'm splitting out part of the overall API as a separate subroute, i.e. (code simplified for this question)

const mainRouter = express.Router();
const bananaRouter = express.Router();
const appleRouter = express.Router();

bananaRouter.get('/banana/hello', (req, res) => { /* ... */ });

mainRouter.all('/banana/*', bananaRouter);
mainRouter.all('/apple/*', appleRouter);

This works. But I don't want to specify the full '/banana/hello' in every single route, and would much prefer '/hello'.

How can I do that?

CodePudding user response:

Use .use() with a path prefix (no wildcard) instead of .all(). .use() will automatically match a path prefix without a wildcard whereas .get() and .all() will not and this will then set up your router better. So, do this to register the router:

// send all /banana prefixed urls to the bananaRouter
mainRouter.use('/banana', bananaRouter);

Then, inside of that router, you don't use the /banana part of the path:

// will match /banana/hello
bananaRouter.get('/hello', (req, res) => { /* ... */ });

In general, you will use .use() for routers and other middleware, not .all().

  • Related