How to Access POST Form Fields in Express
When handling POST requests in Express.js, accessing form field values can be different depending on the version you're using. Here's a guide on how to do it in different versions:
Express 4.0 to 4.15
To parse POST form data in Express 4.0 to 4.15, you'll need to install the body-parser middleware:
npm install --save body-parser
Then, require and use the bodyParser middleware in your Express application:
var bodyParser = require('body-parser'); app.use(bodyParser.json()); // for JSON-encoded bodies app.use(bodyParser.urlencoded({ extended: true })); // for URL-encoded bodies
With the middleware in place, you can access the form field values through the req.body object:
app.post('/userlogin', function(req, res) { var email = req.body.email; }
Express 4.16.0 and Above
Starting Express 4.16.0, you can use the express.json() and express.urlencoded() middleware directly without installing a separate package. Simply add them to your Express application:
app.use(express.json()); // for JSON-encoded bodies app.use(express.urlencoded()); // for URL-encoded bodies
Accessing the form field values remains the same through the req.body object:
app.post('/userlogin', function(req, res) { var email = req.body.email; }
Note:
The above is the detailed content of How to Access POST Form Fields in Different Express.js Versions?. For more information, please follow other related articles on the PHP Chinese website!