Body-parser Middleware in Node.js
Body-parser is the Node.js body-parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it. It’s commonly used in web applications built with Express.js to handle form submissions, JSON payloads, and other types of request bodies.
Steps to Setup a body-parser Module
Step 1: First init the node app using the below command.
npm init -y
Step 2: You can visit the link to Install the body-parser module. You can install this package by using this command.
npm install body-parser express ejs
Step 2: After installing body-parser you can check your body-parser version in the command prompt using the command.
npm version body-parser
Project Structure:
The updated dependencies in your package.json file will look like this:
"dependencies":{
"body-parser": "^1.20.2",
"express": "^4.18.2",
"ejs": "^3.1.9"
}
Example: Below is an example of body-parser middleware in Node.js.
<!DOCTYPE html>
<html>
<head>
<title>Body-Parser Module Demo</title>
</head>
<body>
<h1>Demo Form</h1>
<form action="saveData" method="POST">
<pre>
Enter your Email : <input type="text"
name="email"> <br>
<input type="submit" value="Submit Form">
</pre>
</form>
</body>
</html>
const bodyparser = require('body-parser')
const express = require("express")
const path = require('path')
const app = express()
let PORT = process.env.port || 3000
// View Engine Setup
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")
// Body-parser middleware
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())
app.get("/", function (req, res) {
res.render("SampleForm")
});
app.post('/saveData', (req, res) => {
console.log("Using Body-parser: ", req.body.email)
})
app.listen(PORT, function (error) {
if (error) throw error
console.log("Server created Successfully on PORT", PORT)
})
Run the index.js file using the below command:
node index.js
Now Open the browser and type the below URL and you will see the Demo Form as shown below:
http://localhost:3000/
Now submit the form and then you will see the following output:
But if we do not use this body-parser middle, then while parsing, an error will occur as shown below:
So this is how you can use the body-parser module for parsing incoming request bodies in middleware before you handle it.