Getting ready

Middleware functions have the following signature:

app.use((request, response, next) => { 
    next() 
}) 

The signature is very similar to writing route handlers. In fact, a middleware function can be written for a specific HTTP method and a specific path route, and will look like this, for example:

app.get('/', (request, response, next) => { 
    next() 
}) 

So, if you are wondering what the difference is between route handlers, and middleware functions, the answer is simple: their purpose.

If you are writing route handlers, and the request objects and/or the response object is modified, then you are writing middleware functions.

In this recipe, you will see how to use a middleware function to restrict access to certain paths or routes that depend on a certain condition. 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 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.76.30