Approach 1 Using body-parser Middleware

We are using the body-parser third-party middleware to parse and extract the form data from the POST requests in the Express.js application. We need to install the middleware first by using the command npm install body-parser. This middleware has 4 parsing modules JSON, Text, URL-encoded, and raw data sets.

Example: In the below example, we have used the body-parser middleware in the Express application which accesses the data from the POST requests.

Javascript




//app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// using body-parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
// defining a route for the form
app.post('/submit', (req, res) => {
    // accessing form fields from req.body
    const username = req.body.username;
    const password = req.body.password;
    // verification steps
    if (!username || !password) {
        return res.status(400).send('Username and password are required.');
    }
    // sending a response
    res.send(`Received: Username - ${username}, Password - ${password}`);
});
// start the server
const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});


Output:

How to access POST form fields in Express JS?

Express JS is used to build the application based on Node JS can be used to access the POST form fields. When the client submits the form with the HTTP POST method, Express JS provides the feature to process the form data. By this, we can retrieve the user input within the application and provide a dynamic response to the client.

Different ways to access the POST form filed in Express are defined below:

Table of Content

  • Using body-parser Middleware
  • Using multer Middleware

Similar Reads

Approach 1: Using body-parser Middleware:

We are using the body-parser third-party middleware to parse and extract the form data from the POST requests in the Express.js application. We need to install the middleware first by using the command npm install body-parser. This middleware has 4 parsing modules JSON, Text, URL-encoded, and raw data sets....

Approach 2: Using multer Middleware:

...

Contact Us