Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 12, 2022 07:19 pm GMT

Writing custom middleware functions in NodeJS

Middleware is any code that runs on the server between getting a request and a response. Middleware functions in NodeJS have access to the request object, the response object and the next function.

function middleFunc(req,res,next){    req.message:'Hello'    next()}

In the example above, the function middleFunc is a middleware function that takes three parameters: req,res,and next. The function sets a req.message to 'Hello'.

Middleware functions do not end the request-response cycle but they have to call next() to either pass execution to the next middleware function or the request handler itself. If next() function is not called, the request will hang.

A middleware function can be run by passing it between the path and callback function of the request handler.

app.get('/',middleFunc,(req,res)=>{    res.json(req.message)})

Here, middleFunc will run first then when next() is called, the execution is passed to the request handler which prints the message.

It is also possible to rewrite the middleware function as an Application-level middleware like this,

app.use((req,res,next)=>{    req.message = 'Hello'    next()})

Original Link: https://dev.to/shemasurge/writing-custom-middleware-functions-in-nodejs-26ee

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To