ExpressJS body-parser is a body parsing middleware which parses incoming request bodies.
You can use body-parser module when you need to parse form data sent by a user by submitting a web form, to parse JSON payloads in REST APIs.
Installing body-parser
You can install body-parser module by using the following command.
npm install body-parser
Parsers in body-parser
This module provides the following parsers-
- JSON body parser- For parsing JSON. Though there is a built-in middleware express.json() which can do the same task.
- URL-encoded form body parser- Parses urlencoded bodies (form data - application/x-www-form-urlencoded)
- Raw body parser- Parses request body as a Buffer
- Text body parser- Parses request body as a string
body-parser middleware example with ExpressJS
In the example there is a form which has name and email inputs and submit button to submit the form.
This form is parsed using body-parser in a POST request. There is another route for JSON parser.
views\person.html
<!DOCTYPE html>
<html>
<head>
<title>Person Form</title>
</head>
<body>
<form action="/savePerson" method="post">
<label for="name">Enter Name</label>
<input type="text" name="name">
<br/>
<label for="email">Enter email</label>
<input type="text" name="email">
<br/>
<button type="submit">Submit</button>
</form>
</body>
The example uses express.Router() to create modular route definitions.
routes\routes.js
There are 3 route definitions. First is get request for rendering the html file for root path.
There is a POST request for the route '/savePerson' which uses bodyParser.urlencoded()
There is a POST request for the route '/api/Person' which uses bodyParser.json()
const express = require('express');
const path = require('path');
const router = express.Router();
router.get('/', (req, res) => {
const view = path.join(__dirname, '..', 'views', 'person.html');
res.sendFile(view);
})
router.post('/savePerson', (req, res) => {
const name = req.body.name;
console.log(name);
const email = req.body.email;
console.log(email);
res.send('<h3>Your name is ' + name + ' and email is ' + email + '</h3>');
})
router.post('/api/Person', (req, res) => {
const name = req.body.name;
console.log(name);
const email = req.body.email;
console.log(email);
// Then Logic to save Person data
res.status(201).send("Data Saved Successfully");
})
module.exports = router;
app.js
This is the file where route definitions are imported. You'll import 'body-parser' too to parse the request body.
const express = require('express');
const appRoutes = require('./routes/route')
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: true}));
// parse application/json
app.use(bodyParser.json())
// routes
app.use(appRoutes);
//Server
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Run the application using the following command
node app.js
If application starts successfully access the URL localhost:3000 which should render a form.
On submitting the form
In the console you should see the logs too
node app.js Example app listening on port 3000 TestUser TestUser@tu.com
For the other route you can use Postman to create a POST request with the JSON body.
{
"name": "Suresh",
"email": "suresh@su.com"
}
That's all for the topic Express body-parser With Examples. If something is missing or you have something to share about the topic please write a comment.
You may also like
- ExpressJS Middleware Functions
- ExpressJS Routing With Examples
- ExpressJS Redirect Using res.redirect()
- ExpressJS res.render() Function
- ExpressJS Query Parameters
- Routing in React With Examples
- NoClassDefFoundError in Java
- How to Convert String to float in Java
- Java Reflection – Class Fields
- Spring Autowiring Using @Autowired Annotation


No comments:
Post a Comment