简体   繁体   中英

What is Middleware in Express JS

Hi Guys In Express Framework we use middleware like for body parser

Eg:-

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

What is Middleware and what is the middleware in Express js , How exactly it works in Exprees js and how can we create customize Middleware in Express Js ??

Middleware is pretty much explanatory by its name. We use middleware to do the specific tasks before actually calling the controller/function.

router.post("/",roleGrant.grantAccess('readAny', 'currency'),validate(authValidation.add),function (req,res){
    currencyDAL.add(req.body,function (data){
        const response = responseSchema.responseSchema(data);
        response.status_code == 1 ? res.status(200).json(response) : res.status(401).json(response)
    })
})

So you can see here is a post API for currency, but before the calling function, I am calling to middleware, first roleGrand to whether the user can call currency API, then I am calling validation middleware to make sure user put all the required things to call post API of currency.

If the user passes both middlewares, then the API function/controller will call, otherwise, API will send a response without calling the API controller

body-parser is used in POST requests. It extracts the entire body portion of an incoming request stream and exposes it on req.body. Like here I am using body-parser to get POST request's body.

Whenever you send a request to your server with some data. To parse the body of that particular request and extract data from it, we use body-parser module as a middleware.

A middleware is basically a bridge between two applications to be precise.

Therefore using body parser allows you to access the req.body property of an incoming request by parsing it and forwarding the request object to your API's function that handles that particular URL format.

It has various types of parsers to suit one's needs such as:

  1. JSON
  2. Raw
  3. Text
  4. URL-encoded

For a broader explaination you can visit the docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM