Express Middleware

Express Middleware

MEAN Stack 24-09-2021 Saheb Sutradhar

Express Middleware 

What is Express Middleware ?

Middleware is a function which takes request object , either it returns response to the client or passes the control to the next middleware.

In expressJS all the route handler functions are middleware, because it takes request and terminates the request processing pipeline bu sending request to the client.

 

const express = require('express');
const app = express();
app.listen(2000,()=>{
    console.log("Server is listening PORT 2000")
})
app.get('/',(req,res)=>{
    res.send("Sending response to client")
})

Inbuilt json() middleware 

const express = require('express');
const app = express();
app.listen(2000,()=>{
    console.log("Server is listening PORT 2000")
})

app.use(express.json());

app.get('/',(req,res)=>{
    res.send("Sending response to client")
})

 

express.json()  returns a middleware function , and the job of the function is to read the request and if there is json in the body then it will parse the json into json object.
 
Express Middleware
In the runtime when we receive the request on the server that request goes through the request response pipeline , we call the pipeline (Request processing pipeline). In that pipeline we can have one or more middleware functions . Each middleware function either terminates the process by sending request to the client or passes the control to the next middleware.
 
In real time application we use middleware to check authorization , In the below example we will create a post api and in the middleware we will check if the request body contains firstname property and the firstname is "SAHEB" then it will set the last name "SUTRADHAR" and pass control to the next middleware function , if the request body does not have firstname property and if the name is not "SAHEB" then it will terminate the process there by sending error response to the client .
 
 
const express = require('express');
const app = express();
app.listen(2000,()=>{
    console.log("Server is listening PORT 2000")
})
app.use(express.json());
app.use((req,res,next)=>{
    if(req && req.body.firstname && (req.body.firstname == "SAHEB")){
        req.body.lastname="SUTRADHAR";
        next()
    }
    else{
     res.status(401).send('Name not matched')
    }
});

app.post('/',(req,res)=>{
    res.send(req.body)
})
 
RESULT
 
express middleware
 

Create a custom middleware

Middleware function are normal functions which has three arguments function(req , res , next){}  , it should perform al least  one operation either send response to client or pass control to next middleware , otherwise the request process operation will get stuck .

Once we create a middleware function we need to add or register it to the request process pipeline, there are two ways to register it.

if we use app.use(mifflewareFN) then it will get  applied for all the apis  , We can add a middleware to a particular api follow the below example

const express = require('express');
const app = express();
app.listen(2000,()=>{
    console.log("Server is listening PORT 2000")
})

app.use(express.json())
let nameCheckMiddleware=(req,res,next)=>{
    if(req && req.body && req.body.firstname && (req.body.firstname == "SAHEB")){
        req.body.lastname="SUTRADHAR";
        next()
    }
    else{
     res.status(401).send('Name not matched')
    }
}

app.post('/',[nameCheckMiddleware],(req,res)=>{
    res.send(req.body)
})

 

app.post('/',[middleware1, middleware1],(req,res)=>{}) in all http method we can set one or more than middleware functions.
 
Note : Middleware function are called in sequence , in the sequence you will define the middleware function ,it will maintain the same sequence while getting executed.
 
 

Builtin middleware functions

In express we have many builtin middleware function , check for more Expressjs Built-in Middleware Functions

express.json() we have already seen that why we use this middleware function.

express.urlencoded() This builtin middleware function we use to parse the incoming request with query string and converts it into json object . 

Example : 

const express = require('express');
const app = express();
app.listen(2000,()=>{
    console.log("Server is listening PORT 2000")
})

app.use(express.urlencoded({extended:true}))

app.post('/',[nameCheckMiddleware],(req,res)=>{
    res.send(req.body)
})

 

We need to pass an object with extended property as parameter of urlencoaded function else in the console you will see this warning message body-parser deprecated undefined extended: provide extended option app.js:7:17


express middleware

 

I hope this article is helpful for you , i am very glad to help you thanks for reading

 

 

 

Related Posts

Card image cap

NodeJS Path Module

MEAN Stack 23-09-2021 Saheb Sutradhar

NodeJS path module is the builtin module of nodeJS ,We use the path module to work with the file path, By declaring the below syntax we can import the path modu ...

Card image cap

What is JWT and Why should we use JWT

MEAN Stack 01-10-2021 Saheb Sutradhar

What is JWT and Why should we use JWT , JWT stands for json wen token , JWT we use for authorization not for authentication . ...