Saturday 16 February 2019

Node.js: Express: Middleware function


Middleware functions are intermediary functions that are executed before giving access to the resource, before serving response.

For example, in a typical web application, if user requests for something, you may do below things.
a.   Log the request information.
b.   Check whether user is authorized to access the resource or not.
c.    Finally send response to user.



As you see above image, to serve actual response to the request, it should pass through different middle ware functions. Each middleware function can able to forward the request to next middleware function (or) can directly send the response to the request.

Let us write simple application using middleware.
const app = express();

app.use("/greetMe", function (req, res, next) {
  console.log('Received greetme request', Date.now());
  next();
});

app.use("/greetMe", function (req, res, next) {
  console.log('Authorization successful to the user');
  next();
});

app.get("/greetMe", (req, res) => {res.send("Hello User, Have a great day!!!!")} );

As you see above snippet, ‘use’ function is acting as a middleware. To access /greetMe resource (get method), user has to go through logging and authorization middlewares.


HelloWorld.js
//Load express module
const express = require('express');

//Put new Express application inside app variable
const app = express();

const port = 8080;

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'));

app.use("/greetMe", function (req, res, next) {
  console.log('Received greetme request', Date.now());
  next();
});

app.use("/greetMe", function (req, res, next) {
  console.log('Authorization successful to the user');
  next();
});

app.get("/greetMe", (req, res) => {
 console.log("Serving actual response");
 res.send("Hello User, Have a great day!!!!")
} );


// Start the express application on port 8080 and print server start message to console.
app.listen(port, () => console.log(`Application started listening on port ${port}!`));


Run HelloWorld.js using the command ‘node HelloWorld.js’.
You can see below messages in the console.
Application started listening on port 8080!

Hit the request 'http://localhost:8080/greetMe' in the browser.


You can see below response in browser.


You can see below messages in console.
Received greetme request 1540353195951
Authorization successful to the user
Serving actual response

Things to understand from above example.
a.   Middleware function has access to request and response objects. Middleware function can able to modify request and response objects.
b.   Middleware function calls the next middleware function using next() function.
c.    Middleware function can able to execute code.
d.   Middle ware function can restrict the resource from access. For example, authorization middle ware can send response code 403, if user is not authorized to access the resource.

Order of the middleware functions matter
Middleware functions will execute in the order they defined the application.


For example, if I write authorization middleware before logging middleware, then authorization middleware executes first.
app.use("/greetMe", function (req, res, next) {
  console.log('Authorization successful to the user');
  next();
});

app.use("/greetMe", function (req, res, next) {
  console.log('Received greetme request', Date.now());
  next();
});


HelloWorld.js
//Load express module
const express = require('express');

//Put new Express application inside app variable
const app = express();

const port = 8080;

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'));

app.use("/greetMe", function (req, res, next) {
  console.log('Authorization successful to the user');
  next();
});

app.use("/greetMe", function (req, res, next) {
  console.log('Received greetme request', Date.now());
  next();
});

app.get("/greetMe", (req, res) => {
 console.log("Serving actual response");
 res.send("Hello User, Have a great day!!!!")
} );


// Start the express application on port 8080 and print server start message to console.
app.listen(port, () => console.log(`Application started listening on port ${port}!`));


Run HelloWorld.js using the command ‘node HelloWorld.js’.

You can see below messages in the console.
Application started listening on port 8080!


Hit the request 'http://localhost:8080/greetMe' in the browser

You can see below messages in console.
Authorization successful to the user
Received greetme request 1540353537298
Serving actual response

Reference




Previous                                                 Next                                                 Home

No comments:

Post a Comment