Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  140] [ 2]  / answers: 1 / hits: 48806  / 11 Years ago, wed, december 4, 2013, 12:00:00

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 error and usually the issue is that people do not include app.use(express.bodyParser()); middleware , so I also tried using app.use(express.urlencoded()); and app.use(express.json());, which didn't work 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 myself so I can learn from the experience.*



Thanks



EDIT:
I had to put the bodyparser middleware before the app.router middleware, that fixed it!


More From » json

 Answers
42

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);

[#73911] Monday, December 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frankiebobbyc

Total Points: 18
Total Questions: 85
Total Answers: 104

Location: Norway
Member since Wed, Jul 7, 2021
3 Years ago
;