Express: Middleware
= functions that have access to request object(req) and response object (res) and the next middleware function in the layer (if more than one specified) . The next middleware function is commonly denoted by a variable named
next
.
Middleware allows you to define a stack of actions that you should flow through.
A layer in middleware stack = function which takes as parameters: req, res and next function
app.use() = specify middleware to execute (can call multiple times)
this function is called FOR ALL requests. Notice that the function it calls "myLogger" has important line next() that means it will go on to be processed by
app.get or any other methods implemented.
EXAMPLE 1: middleware that is called ALWAYS regardless of URI request
var express = require('express'); var app = express(); //Simple request time logger app.use(function(req, res, next){ console.log("A new request received at " + Date.now()); //This function call is very important. It tells that more processing is //required for the current request and is in the next middleware function/route handler. next(); }); app.listen(3000);
EXAMPLE 2: if have a get request for / will first execute then go to app.get handler
var express = require('express') var app = express() var myLogger = function (req, res, next) { console.log('LOGGED') next() } app.use(myLogger) app.get('/', function (req, res) { res.send('Hello World!') }) app.listen(3000)
EXAMPLE 3: where you call middleware only if URI is /things then will go next to app.get handler code
var express = require('express'); var app = express(); //Middleware function to log request protocol app.use('/things', function(req, res, next){ console.log("A request for things received at " + Date.now()); next(); }); //Route handler that sends the response app.get('/things', function(req, res){ res.send('Things'); }); app.listen(3000);Now whenever you request any subroute of '/things', only then it'll log the time.
Multiple Layers in Middleware --> MULTIPLE calls to app.use()
A list of Third party middleware for express is available here. Following are some of the most commonly used middlewares, and how to use/mount these:
This is used to parse the body of requests which have payloads attached to them. To mount body parser, we need to install it using npm install --save body-parser and to mount it, include the following lines in your index.js:
var bodyParser = require('body-parser'); //To parse URL encoded data app.use(bodyParser.urlencoded({ extended: false })) //To parse json data app.use(bodyParser.json())
To view all available options for body-parser, visit its github page.
It parses Cookie header and populate req.cookies with an object keyed by cookie names. To mount cookie parser, we need to install it using npm install --save cookie-parser and to mount it, include the following lines in your index.js:
var bodyParser = require('body-parser'); app.use(cookieParser())
It creates a session middleware with the given options. We will discuss its usage in the Sessions section.