Parsing form data in express app manually without body-parser

07 Oct, 2021
Parsing means accessing the data submitted by user with HTML form. When the form is submitted with the ‘GET’ method, data are appended in ‘query string’ and can access easily but when a form is submitted using the ‘POST’ method, it is somewhat difficult to get access over those data since they are encoded because of security purpose. There exist a body-parser NPM method that makes it very easy to parse the data but if we try to implement this parsing method from scratch, there’s involve some steps.
Steps: 
Install Express package
npm install express
Starting express server(set app listener)
app.listen(PORT, callback)
create the route for ‘POST’ form submission and setting up middleware function call
app.post(path, middleware, callback)
create middleware parsing function Excess the encoded form data aap.on() method.Convert the encoded data into string using decodeURIComponent() method.Create an object of user submitted data and assign it to req.body of request object.
Excess the encoded form data aap.on() method.
Convert the encoded data into string using decodeURIComponent() method.
Create an object of user submitted data and assign it to req.body of request object.
Example 1: This example creating a login form.
File: loginForm.ejs 
HTML
<!DOCTYPE html><html lang="en"> <head>    <title>Form data parsing</title></head> <body>    <form action='information' method='POST'>        <div>            <label id='username'>Username</label>            <div>                <input type='text' for='username'                    placeholder='Username'                    name='username'>            </div>        </div>         <div>            <label class='label' id='password'>                Password            </label>             <div>                <input class='input'                    type='password'                    for='password'                    placeholder='Password'                    name='password'>            </div>        </div>         <div class='buttons'>            <button>Login</button>        </div>    </form></body> </html>
File: index.js 
Javascript
// Installing packageconst express = require('express')const path = require('path')const app = express() const PORT = process.env.PORT || 3000 // Middleware functionconst parseData = (req, res, next) => {    if (req.method === 'POST') {        const formData = {}        req.on('data', data => {             // Decode and parse data            const parsedData =                decodeURIComponent(data).split('&')             for (let data of parsedData) {                 decodedData = decodeURIComponent(                        data.replace(/\+/g, '%20'))                 const [key, value] =                        decodedData.split('=')                 // Accumulate submitted                // data in an object                formData[key] = value            }             // Attach form data in request object            req.body = formData            next()        })    } else {        next()    }} // View engine setupapp.set("views", path.join(__dirname))app.set("view engine", "ejs") // Render Login form pageapp.get('/', (req, res) => {    res.render('loginForm')}) // Creating Post Route for loginapp.post('/information', parseData, (req, res) => {     // Retrieve form data from request object    const data = req.body    const { username, password } = data     //Render information in the page    res.send(`      <p><strong>Login Information collected!</strong></p>      <div>      <strong>Username</strong> : ${username}    </div>    <div>      <strong>Password</strong> : ${password}    </div>  `)}) // Setting up listenerapp.listen(PORT, () => {    console.log(`Server start on port ${PORT}`)})
Output: 
Login Form:
Fetched login information:
Example 2: This example creating a registration form.
File: registrationForm.ejs 
HTML
<!DOCTYPE html><html lang="en"> <head>    <title>Form data parsing</title></head> <body>    <form action='information' method='POST'>        <div>            <label id='username'>Username</label>            <div>                <input type='text' for='username'                    placeholder='Username'                    name='username'>            </div>        </div>         <div>            <label id='email'>Email</label>            <div>                <input type='text' for='email'                    placeholder='Email' name='email'>            </div>        </div>         <div>            <label id='password'>Password</label>            <div>                <input type='password' for='password'                    placeholder='Password'                    name='password'>            </div>        </div>         <div>            <label id='confirmPassword'>                Confirm Password            </label>            <div>                <input type='password'                    for='confirmPassword'                    placeholder='Confirm Password'                    name='confirmPassword'>            </div>        </div>         <div>            <label>Sex:                <label>                    <input type='radio'                        name='sex' value='Male'>                    Male                </label>                 <label>                    <input type='radio'                        name='sex' value='Female'>                    Female                </label>            </label>        </div>         <div class='buttons'>            <button>Register</button>        </div>    </form></body> </html>
File: index.js
Javascript
// Installing packageconst express = require('express')const path = require('path')const app = express() const PORT = process.env.PORT || 3000 // Middleware functionconst parseData = (req, res, next) => {    if (req.method === 'POST') {        const formData = {}        req.on('data', data => {             // Decode and parse data            const parsedData =                decodeURIComponent(data).split('&')             for (let data of parsedData) {                 decodedData = decodeURIComponent(                        data.replace(/\+/g, '%20'))                 const [key, value]                    = decodedData.split('=')                 // Accumulate submitted data                // in an object                formData[key] = value            }             // Attach form data in request object            req.body = formData            next()        })    } else {        next()    }} // View engine setupapp.set("views", path.join(__dirname))app.set("view engine", "ejs") // Render Login form pageapp.get('/', (req, res) => {    res.render('registrationForm')}) // Creating Post Route for loginapp.post('/information', parseData, (req, res) => {     // Retrieve form data from request object    const data = req.body    const { username,        email,        password,        confirmPassword,        sex,    } = data     // Printing fetched data in    // developer's console    console.log(data)}) // Setting up listenerapp.listen(PORT, () => {    console.log(`Server start on port ${PORT}`)})
Output: 
Registration Form:
Fetched Registration data and printing it on console:
 
gulshankumarar231
varshagumber28
Node.js-Misc
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React