Languages
[Edit]
EN

Node.js / Express.js - middleware

0 points
Created by:
Wayne
265

In this article, we would like to show you how to create and useĀ middlewareĀ functions inĀ Express.js.

Introduction

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function (next)Ā in express.js applicationā€™s request-response cycle.

They are used to:

  • execute any code,
  • modify req and res objects for tasks like parsing request bodies, adding response headers, authentication etc.
  • end the request-response cycle,
  • call the next middleware function in the stack.

Note:

If the current middleware function doesn'tĀ end the request-response cycle, it must callĀ next()Ā to pass control to the next middleware function. Otherwise, the request will be left hanging.

Practical example

In this example, we create a simple request tracker that prints every request date in the console and then calls the next()Ā function.

const express = require('express');
const app = express();

app.use((req, res, next) => {
  // get and print current date
  const date = new Date();
  console.log('A new request registered at ' + date);

  // call the next middleware function in the stack
  next();
});

app.listen(3000);

Now when you run the application and send any request (e.g just openĀ http://localhost:3000/) you should get the following result in the console:

A new request registered at Fri Aug 27 2021 16:41:27 GMT+0200 (Central European Summer Time)

Assigning to a specific route

To assign the middleware to a specific routeĀ and all its subroutes, you need to specify that route as the first argument of theĀ app.use().

Example:

const express = require('express');
const app = express();

// request tracker
app.use('/users', (req, res, next) => {
  // get and print current date
  const date = new Date();
  console.log('A new request received at ' + date);

  // call the next middleware function in the stack
  next();
});

app.listen(3000);

Now the middleware won't work for localhost:3000/. You need to request any subroute of '/users', only then it will print the time.

Request:

http://localhost:3000/users

Console:

A new request received at Fri Aug 27 2021 16:51:11 GMT+0200 (Central European Summer Time)

See also

References

Native Advertising
šŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ā¤ļøšŸ’» šŸ™‚

Join