snippetjavascriptexpressCritical
How to access POST form fields in Express
Viewed 0 times
formhowaccesspostexpressfields
Problem
Here is my simple form:
Here is my Express.js/Node.js code:
I tried
When I change to a Get call, it works, so .. any idea?
Email:
Here is my Express.js/Node.js code:
app.post('/userlogin', function(sReq, sRes){
var email = sReq.query.email.;
}I tried
sReq.query.email or sReq.query['email'] or sReq.params['email'], etc. None of them work. They all return undefined. When I change to a Get call, it works, so .. any idea?
Solution
Things have changed once again starting Express 4.16.0, you can now use
This was different starting Express 4.0 to 4.15:
and then:
The rest is like in Express 3.0:
Firstly you need to add some middleware to parse the post data of the body.
Add one or both of the following lines of code:
Then, in your handler, use the
Note that the use of
...is equivalent to:
Security concerns exist with
express.json() and express.urlencoded() just like in Express 3.0.This was different starting Express 4.0 to 4.15:
$ npm install --save body-parserand then:
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
}));The rest is like in Express 3.0:
Firstly you need to add some middleware to parse the post data of the body.
Add one or both of the following lines of code:
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodiesThen, in your handler, use 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;
// ...
});Note that the use of
express.bodyParser() is not recommended.app.use(express.bodyParser());...is equivalent to:
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());Security concerns exist with
express.multipart(), and so it is better to explicitly add support for the specific encoding type(s) you require. If you do need multipart encoding (to support uploading files for example) then you should read this.Code Snippets
$ npm install --save body-parservar bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies// 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;
// ...
});app.use(express.bodyParser());Context
Stack Overflow Q#5710358, score: 1416
Revisions (0)
No revisions yet.