An Express application can use any of the below mentioned types of middleware:
-
Application-level middleware : app.use
-
Router-level middleware : router.use
-
Error handling middleware app.use(err,req,res,next)
-
Built-in middleware : express.static,express.json,express.urlencoded
-
Third-party middleware : bodyparser,cookieparser
Router-level Middleware
Express router is a class which helps us to create router handlers. By router handler i mean to not just providing routing to our app but also can extend this routing to handle validation, handle 404 or other errors etc.
A router object is an isolated instance of middleware and routes. It has capable of performing middleware and routing functions
A router behaves like middleware itself, so you can use it as an argument to app.use() or as the argument to another router’s use() method.
Once you’ve created a router object, you can add middleware and HTTP method routes (get, post) to it just like an application.
Example
// invoked for any requests passed to this router
router.use(function(req, res, next) {
// .. some logic here .. like any other middleware
next();
});
// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', function(req, res, next) {
// ..
});
You can then use a router for a particular root URL in this way separating your routes into files or even mini-apps.
// only requests to /calendar/* will be sent to our "router"
app.use('/calendar', router);
The Complete Example for router Example : sample.js
var express = require('express');
var app = express()
var router = express.Router()
// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
// .. some logic here .. like any other middleware
var currentDate = new Date;
console.log('Time:', currentDate.toLocaleString() )
next()
})
// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.use('/user/:id', function (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}, function (req, res, next) {
console.log('Request Type:', req.method)
next()
})
// a middleware sub-stack that handles GET requests to the /user/:id path
router.get('/user/:id', function (req, res, next) {
// if the user ID is 0, skip to the next router
if (req.params.id === '0') next('route')
// otherwise pass control to the next middleware function in this stack
else next()
}, function (req, res, next) {
console.log('regular');
// render a regular page
res.send('regular')
})
// handler for the /user/:id path, which renders a special page
router.get('/user/:id', function (req, res, next) {
console.log(req.params.id)
res.send('special')
})
// mount the router on the app
app.use('/', router)
app.listen(3000, function() {
console.log('Listenint Port : 3000 ');
});
As the name implies will be executed before your routes get invoked. We can use middleware for routes such as to log every request before its invoked or finding.next() function will take your router to next routes.
Run the below example with API request “http://localhost:3000/api”
var express = require("express");
var app = express();
//Creating Router() object
var router = express.Router();
// Router middleware, mentioned it before defining routes.
router.use(function(req,res,next) {
console.log("/" + req.method);
next();
});
router.use("/user/:id",function(req,res,next){
console.log('Passed Value : ' + req.params.id)
if(req.params.id == 0) {
res.json({"message" : "Pass ID other than 0"});
}
else next();
});
// Provide all routes here, this is for Home page.
router.get("/",function(req,res){
res.json({"message" : "Welcome Express Router"});
});
router.get("/user/:id",function(req,res){
res.json({"message" : "Express Router with Param "+req.params.id});
});
// Tell express to use this router with /api before ex - http://localhost:3000/api .
app.use("/api",router);
// Listen to this Port
app.listen(3000,function(){
console.log("Listening Port : 3000");
});