Middleware

1. What is Middleware?

  • Similar to automobile factory processes, adds necessary functionality to requests or removes problematic items

  • One of Express's biggest advantages

  • Can easily apply tasks that might be cumbersome in servers implemented with Node.js alone

2. Situations When Using Middleware

(1) When structuring body (payload) included in POST requests (when you want to easily extract it)

Code to receive HTTP request body with Node.js

let body = [];
request
  .on('data', (chunk) => {
    body.push(chunk);
  })
  .on('end', () => {
    body = Buffer.concat(body).toString();
    // payload is contained in body variable as string
    // combine chunks on network and convert buffer to string
  });

Code using body-parser middleware

From Express v4.16.0, use built-in middleware express.json() without installing body-parser

If there's an error using express.json() middleware? β†’ Add {strict: false} to options

(2) When CORS headers need to be attached to all requests/responses

Applying CORS to Node.js

Using cors middleware: Allow CORS for all requests

Using cors middleware: Allow CORS for specific requests

(3) When checking URL or method for all requests

Apply middleware to all requests using use method

(4) When checking if user authentication information is contained in request headers

Determine if there's a token in HTTP request, return success if already logged in user, error if not

Last updated