"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to access POST form fields in Express.js?

How to access POST form fields in Express.js?

Posted on 2025-04-15
Browse:917

How Do I Access POST Form Fields in Express.js?

Accessing POST Form Fields in Express: A Guide

When working with forms, accessing POST form fields in Express can be a straightforward process. However, subtle changes in Express versions have introduced some variations in the approach.

Express 4.16.0 and Later

Starting with Express 4.16.0, accessing POST form fields has been simplified with the introduction of express.json() and express.urlencoded. These middleware functions parse JSON and URL-encoded bodies, respectively.

To use this approach, install express:

$ npm install express

and include the following middleware in your Express application:

app.use(express.json());       // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies

Once these middleware are in place, you can access POST form fields using the req.body object:

// assuming POST: name=foo&color=red            <-- URL encoding
//
// or       POST: {"name":"foo","color":"red"}  <-- JSON encoding

app.post('/test-page', function(req, res) {
    var name = req.body.name,
        color = req.body.color;
    // ...
});

Express 4.0 to 4.15

Prior to Express 4.16.0, handling POST form fields involved installing the body-parser package and using its middleware.

$ npm install --save body-parser

In your Express application, include the following lines:

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 

With this configuration, accessing POST form fields is similar to the approach in Express 4.16.0:

app.post('/test-page', function(req, res) {
    var name = req.body.name,
        color = req.body.color;
    // ...
});

Note: The use of express.bodyParser() is not recommended and is equivalent to the combined use of express.json(), express.urlencoded(), and express.multipart(). Avoid express.bodyParser() unless you specifically require multipart encoding support, which comes with security concerns. For multipart encoding, refer to Express documentation.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3