Reputation: 10208
I have a node.js server with express Framework.
var express = require('express');
var http = require('http');
var api_helper = require('./helpers/api_helper');
var app = express();
app.use(app.router);
app.use(express.bodyParser());
app.set('port', process.env.PORT || 8081);
app.post('/api/nodev1/users/login', function(req, res){
var email = req.param('email', null);
var password = req.param('password', null);
console.log(email);console.log(password);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
When I try to post a request to /api/nodev1/users/login I cannot read the parameters. I am trying with curl as follows:
curl -d "[email protected]" -d "password=mypassword" http://localhost:8081/api/nodev1/users/login
The email and password are undefined.
Upvotes: 2
Views: 9246
Reputation: 12987
You have to move app.use(app.router)
below app.use(express.bodyParser())
. app.router
is just a hook in which stage to handle your routes. And if it comes before bodyParser
the body is not parsed.
Your code could look like this (in case I didn't manage to explain understandable):
var app = express();
app.use(express.bodyParser());
app.set('port', process.env.PORT || 8081);
app.use(app.router);
// I added following line so you can better see what happens
app.use(express.logger('dev'));
app.post('/api/nodev1/users/login', function(req, res){ ... }
Offtopic remark: express.bodyParser()
should only be used when you have file-uploads. And then you have to take care of deleting temp-files. If you don't have file-uploads, you are better off with only
app.use(express.json());
app.use(express.urlencoded());
I just wanted to add this in case you didn't know. I ran in problems because I didn't know...
Edit for Express 4
Thanks to @jonathan-ong there is no app.use(app.router)
since Express 4:
All routing methods will be added in the order in which they appear. You should not do
app.use(app.router)
. This eliminates the most common issue with Express.In other words, mixing
app.use()
andapp[VERB]()
will work exactly in the order in which they are called.
Read more: New features in 4.x.
Upvotes: 7
Reputation: 11052
edit - nope, see other answer about middleware order!
change req.param
to req.body.x
:
app.post('/api/nodev1/users/login', function(req, res){
var email = req.param('email', null);
var password = req.param('password', null);
console.log(email);console.log(password);
});
to
app.post('/api/nodev1/users/login', function(req, res){
var email = req.body.email);
var password = req.body.password);
console.log(email); console.log(password);
});
Upvotes: 0