Writing router-level middleware functions
Router-level middleware functions are only executed inside a router. They are usually used when applying a middleware to a mount point only or to a specific path.
Getting ready
In this recipe, you will create a small logger router-level middleware function that will only log requests to paths mounted or located in the router's mounted path. Before you start, create a new package.json
file with the following content:
{ "dependencies": { "express": "4.16.3" } }
Then, install the dependencies by opening a Terminal and running:
npm install
How to do it...
- Create a new file named
router-level.js
- Initialize a new ExpressJS application and define a router:
const express = require('express') const app = express() const router = express.Router()
- Define our logger middleware function:
router.use((request, response, next) => { console.log('URL:', request.originalUrl) next() })
- Mount the Router...