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.
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; // ... });
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.
The above is the detailed content of How Do I Access POST Form Fields in Express.js?. For more information, please follow other related articles on the PHP Chinese website!