I'm working on an API with NodeJS and Express (and more stuff like mongo, sockets, etc) but i'm stuck on a very simple step i believe, i'm just trying to get the information from the POST req
object, but i get an error when trying to access req.body
Here's what i have:
var express = require('express'),
http = require('http'),
path = require('path'),
fs = require('fs'),
io = require('socket.io');
dynroute = require('dynroute');
var app = express();
app.set('port', process.env.PORT || 3999);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(app.router);
app.use(express.bodyParser());
app.post('/user', function(req, res) {
console.log(JSON.stringify(req.body));
res.send(req.body.self);
});
http.createServer(app).listen(app.get('port'), function ()
{
console.log('App Server is now running at:' + app.get('port'));
});
On the console.log(JSON.stringify(req.body));
i get undefined
and on the res.send(req.body.self);
i get TypeError: Cannot read property 'self' of undefined
I've been seaching for this type of errors and usually the issue is that people do not include app.use(express.bodyParser());
middleware , i also tryied using app.use(express.urlencoded());
and app.use(express.json());
, didn't worked either.
If i do a console.log(req)
i can see the entire object but i do not get to see body
or any of the content i'm passing when doing the POST request from a client (i'm passing it as JSON).
*I know i could use restify
or sails.js
to build APIs within Node but i want to do everything by my own so i can learn from the experience.
Thanks
EDIT:
I had to put the bodyparser
middleware before the app.router
middleware, that fix it!
Move the bodyParser
middleware above the router
middleware!
var app = express();
app.set('port', process.env.PORT || 3999);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(app.router);
For me @kevinblanco's note of "I had to put the bodyparser middleware before the app.router middleware, that fix it!" did it for me. Putting it in a separate answer since its buried at the bottom.
Your code will need to look something like this:
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// My routing here
BodyParser is no longer bundled with Express
npm install body-parser
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
Content-Type = "application/json"
should be one of the Request Headers