An Express application can use any of the below mentioned types of middleware:
-
Application-level middleware : app.use
-
Router-level middleware : router.use
-
Error handling middleware app.use(err,req,res,next)
-
Built-in middleware : express.static,express.json,express.urlencoded
-
Third-party middleware : bodyparser,cookieparser
Third-party Middlewares
In some cases we will be adding some extra features to our back end
Install the Node.js module for the required functionality, then load it in your app at the application level or at the router level
Example : body-parser
This third party middleware will Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
To install run the below command
npm install body-parser
Example : app.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
app.post('/save',(req,res)=>{
res.json({
"status":true,
"payload":req.body
})
})
var server = app.listen(3000, function() {
console.log('Listenint Port : 3000 ');
});
Run the command in node terminal
node app.js
And browse the path in postman : “http://localhost:3000/save”
Output
{
"status": true,
"payload": {}
}