Skip to content
Related Articles

Related Articles

Parsing form data in express app manually without body-parser
  • Last Updated : 22 Jun, 2020

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.

Example 1: This example creating a login form.

File: loginForm.ejs




<!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






// Installing package
const express = require('express')
const path = require('path')
const app = express()
  
const PORT = process.env.PORT || 3000
  
// Middleware function
const 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 setup
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")
  
// Render Login form page
app.get('/', (req, res) => {
    res.render('loginForm')
})
  
// Creating Post Route for login
app.post('/information', parseData, (req, res) => {
  
    // Retrive 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 listener
app.listen(PORT, () => {
    console.log(`Server start on port ${PORT}`)
})

Output:

  • Login Form:
  • Fetched login information:

Exapmle 2: This example creating a registration form.

File: registrationForm.ejs




<!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




// Installing package
const express = require('express')
const path = require('path')
const app = express()
  
const PORT = process.env.PORT || 3000
  
// Middleware function
const 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 setup
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")
  
// Render Login form page
app.get('/', (req, res) => {
    res.render('registrationForm')
})
  
// Creating Post Route for login
app.post('/information', parseData, (req, res) => {
  
    // Retrive 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 listener
app.listen(PORT, () => {
    console.log(`Server start on port ${PORT}`)
})

Output:

  • Registration Form:
  • Fetched Registration data and printing it on console:
My Personal Notes arrow_drop_up
Recommended Articles
Page :