Express.js Middleware are different types of functions that are invoked by the Express.js routing layer before the final request handler. As the name specified, Middleware appears in the middle between an initial request and final intended route. In stack, middleware functions are always invoked in the order in which they are added.
Middleware is commonly used to perform tasks like body parsing for URL-encoded or JSON requests, cookie parsing for basic cookie handling, or even building JavaScript modules on the fly.
Middleware functions are the functions that access to the request and response object (req, res) in request-response cycle.
A middleware function can perform the following tasks:
Following is a list of possibly used middleware in Express.js app:
Let's take an example to understand what middleware is and how it works.
Let's take the most basic Express.js app:
File: simple_express.js
var express = require('express'); var app = express(); app.get('/', function(req, res) { res.send('Welcome to rookienerd!'); }); app.get('/help', function(req, res) { res.send('How can I help You?'); }); var server = app.listen(8000, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) })
You see that server is listening.
Now, you can see the result generated by server on the local host http://127.0.0.1:8000
Output:
Let's see the next page: http://127.0.0.1:8000/help
Output:
Note: You see that the command prompt is not changed. Means, it is not showing any record of the GET request although a GET request is processed in the http://127.0.0.1:8000/help page.
If you want to record every time you a get a request then you can use a middleware.
See this example:
File: simple_middleware.js
var express = require('express'); var app = express(); app.use(function(req, res, next) { console.log('%s %s', req.method, req.url); next(); }); app.get('/', function(req, res, next) { res.send('Welcome to rookienerd!'); }); app.get('/help', function(req, res, next) { res.send('How can I help you?'); }); var server = app.listen(8000, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) })
You see that server is listening.
Now, you can see the result generated by server on the local host http://127.0.0.1:8000
Output:
You can see that output is same but command prompt is displaying a GET result.
Go to http://127.0.0.1:8000/help
As many times as you reload the page, the command prompt will be updated.
Note: In the above example next() middleware is used.
Middleware example explanation