Body Parser in Node JS | Express JS Body Parser express js

Body Parser middleware was earlier a part of express js . For Express 4.16 and above, we have to install it separately.

Body Parser is a middleware of Node JS used to handle HTTP POST request. Body Parser can parse string based client request body into JavaScript Object which we can use in our application.

To include body-parser in our application, use following code. The bodyParser object has two methods, bodyParser.json() and bodyParser.urlencoded(). The data will be available in req.body property.

req.body contains data ( in key-value form ) submitted in request body. The default value is undefined.

Form Data

Use bodyParser to parse HTML Form Data received through HTTP POST method. Create a separate HTML Form with inputs. Use name attributes in all input controls. Set the method (in html form ) to POST and action to path of Post request.

   
    const express=require('express');
    const app=express();
    
    const bodyParser=require('body-parser'); 
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false })); 
    
    app.post('formdata',(req,res)=>{
        console.log(req.body);
        res.json(req.body);
    });

HTML Page

 
    <form method="post" action="127.0.0.01:3000/formdata">
        <input type="text" name="username" required>
        <input type="password" name="userpass" required>
        <button>Send</button>
    <form>