Router

A `router` object is an instance of middleware and routes. You can think of it as a "mini-application," capable only of performing middleware and routing functions. Every Express application has a built-in app router.

A router behaves like middleware itself, so you can use it as an argument to app.use() or as the argument to another router’s use() method.

The top-level express object has a Router() method that creates a new router object.

Once you’ve created a router object, you can add middleware and HTTP method routes (such as get, put, post, and so on) to it just like an application. For example:

// invoked for any requests passed to this router
router.use((req, res, next) => {
// .. some logic here .. like any other middleware
next();
});
// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', (req, res, next) => {
// ..
});

You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps.

// only requests to /calendar/* will be sent to our "router"
app.use('/calendar', router);

Keep in mind that any middleware applied to a router will run for all requests on that router’s path, even those that aren’t part of the router.

Methods

{% include api/en/5x/router-all.md %}
{% include api/en/5x/router-METHOD.md %}
{% include api/en/5x/router-param.md %}
{% include api/en/5x/router-route.md %}
{% include api/en/5x/router-use.md %}