An Interest In:
Web News this Week
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
- March 14, 2024
- March 13, 2024
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To