Middleware is a function which has the access of request object, response object and and the next function in the application’s request-response cycle. It can process the request before the server send a response. Next is used to pass control to the next middleware function. If not the request will be left hanging or open.
Advantages of Middleware:-
It can works on the request object multiple time before server works on it.
It is used to give access of sensitive part of website to only authorized user .
It is used to give logging authenticate functionality.
It is used to set headers in HTTP headers.
It helps in optimization.
Syntax
function (req,res,next){
//body
}
Example
const express = require('express')
const app = express()
const middle = function (req, res, next) {
console.log('LOGGED')
next()}
app.use(middle)
app.get('/', (req, res) => {
res.send('Hello World!')})
app.listen(3000)
Output
LOGGED
Hello World
Chaining In Middleware
If there are many middleware function has to work between request object and response object then with the help of next function we can execute next middleware one after another.
Example
const middle1=(req,res,next)=>{
console.log('Middleware1')
next()
}
const middle2=(req,res,next)=>{
console.log('Middleware2')
next()
}
const middle3=(req,res,next)=>{
console.log('Middleware3')
next()
}
app.get('/abhi',middle1,middle2,middle3,(req,res)=>{
console.log("Hello world")
res.send("Hy")
})
app.listen(8080);
console.log('Server is listening on port 8080');
Output
Server is listening on port 8080
database connected
Middleware1
Middleware2
Middleware3
Hello world
Are you new to node.js or Just started learning and struggling with node.js project? We have team of node.js developer to help you in node.js project, assignment and for learning node.js at affordable price.
Comments