Functions which can retrieve the request object, response object and the next middleware function in the application’s request-response cycle are Middleware.
The concept behind middleware is same as Filters in other languages.
Features of middleware:
- It can modify the request and the response objects.
- It can end the request-response cycle.
- It can call the next middleware function
The middleware function must call to the next() function to pass the control to the next middleware, otherwise, the request will be left unattended.
We often get confused between route handler and the middleware.
app.all(), app.get(), app.post(), app.delete() and app.put() methods are used to define route handler. Whereas app.use() method is used to define the middleware.
To understand middleware let’s take an example. Suppose we have a home and profile page. we want the user to be logged in to visit these pages.Here is how the Middleware for these pages would look like:
var app = require("express")();
function checkLogin()
{
return true;
}
app.use(function(req, res, next){
if(checkLogin())
{
console.log(" User is logged in");
next();
}
else
{
console.log("You are not logged in!!!");
}
})
app.get("/home", function(req, res, next){
console.log("This is the home page");
});
app.get("/profile", function(req, res, next){
console.log("This is the profile page");
});
app.listen(3000);
In the above code checkLogin function is a middleware function, So whenever any request would come first it will call checkLogin function and then pass the request to the next route handler.
So if you open a browser and type http://localhost:3000/home
In console output would be:
User is logged in
This is the home page
Here app.use() may seem similar to app.all() but there are a lot of differences between them which makes app.use() perfect for declaring middlewares. Let's see few difference between the two:
1) app.use() takes only one callback whereas app.all() can take multiple callbacks.
2) app.use() only see whether URL starts with the specified path where app.all() will match complete path.
3) 3) Another difference is if we call next() method inside a middleware it will invoke the next middleware or router handler depending on the order. But if we call next() method inside a router handler, it will invoke the next route handler only.
That's why we should declare middleware above all route handlers.
0 Comment(s)