What is express middleware
Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
Major task of middleware
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware in the stack.
Example
- First Create new node application and create package.json , index.js and install node modules express and body- praser by following commands.
npm install express npm install body-parser
- Write following code into index.js
var express = require('express') var app = express() const bp= require('body-parser') app.use(bp.urlencoded({extended: false})); app.use(bp.json()); var mfun = function(req, res, next) { console.log('middleware is called'); console.log(req.body.name); console.log(req.body.fname); next(); } app.use(mfun); app.get('/', function (req, res) { res.send('GET Request') }) app.post('/', function (req, res) { res.send('POST Request') }) app.listen(3000)
- Run the program and start postman to see results
nodemon index.js
Output