Writing configurable middleware functions
A common pattern for writing middleware functions is to wrap the middleware function inside another function. The result of doing so is a configurable middleware function. They are also higher-order functions, that is, a function that returns another function.
const fn = (options) => (response, request, next) => { next() }
Usually an object is used as an options
parameters. However, there is nothing stopping you from doing it in your own way.
Getting ready
In this recipe, you will write a configurable logger middleware function. 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...
What your configurable middleware function will do is simple: it will print the status code and the URL when a request is made.
- Create a new file named
middleware-logger.js
- Export a function...