Fast middleware

Middleware is a function connected to the routing process and can perform any operation at a certain point in the chain (depending on the operation we want to perform).

Middleware is a function connected to the routing process and can perform any operation at a certain point in the chain (depending on the operation we want to perform).

Usually used to edit the request or response object, or to terminate the request before it reaches the routing handler code.

The middleware is added to the execution stack as follows:

app.use((req, res, next) => { /* */ })

This is similar to defining a route, but in addition to the Request and Response object instances, we also referenceNextMiddleware function, we assign it to a variablenext.

We always callnext()At the end of our middleware function in order to pass execution to the next handler. Unless we want to end the response prematurely and send it back to the client.

You usually use the following forms of prefabricated middleware:npmpackage. Can find a lot of availableHere.

An example iscookie-parser, Used to parse the cookie intoreq.cookiespurpose. You can install usingnpm install cookie-parserSo you can use it:

const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')

app.get(’/’, (req, res) => res.send(‘Hello World!’))

app.use(cookieParser()) app.listen(3000, () => console.log(‘Server ready’))

By using it as the second parameter of the route definition, we can also set the middleware function to run only for specific routes (rather than for all routes):

const myMiddleware = (req, res, next) => {
  /* ... */
  next()
}

app.get(’/’, myMiddleware, (req, res) => res.send(‘Hello World!’))

If you need to store the data generated in the middleware to pass it to subsequent middleware functions or request handlers, you can useRequest.localspurpose. It appends the data to the current request:

req.locals.name = 'Flavio'

Download mine for freeExpress.js manual


More crash tutorials: