Ivan
Ivan

Reputation: 1851

Express: Req.body is undefined after POST request

I'm using the express.bodyParser() before the app.router, and the headers seem to be right, but I'm still getting undefined on req.body:

var app = express();
...

app.use(express.bodyParser());
...
app.use(app.router);

The output of req.headers is this:

{ host: '127.0.0.1:3000',
  connection: 'keep-alive',
  'content-length': '0',
  'cache-control': 'max-age=0',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  origin: 'http://127.0.0.1:3000',
  'user-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36',
  'content-type': 'application/x-www-form-urlencoded',
  referer: 'http://127.0.0.1:3000/register',
  'accept-encoding': 'gzip,deflate,sdch',
  'accept-language': 'es-ES,es;q=0.8' }

And the post is declared like this:

app.post('/register/do', function(req, res) {
    ...
    console.log(req.headers);
    console.log(req.body);
    ...
});

What am I doing wrong?

Upvotes: 5

Views: 9437

Answers (2)

howard
howard

Reputation: 11

I had a alot of problem with this .. this helped me to solve the problem.

var bodyParser = require('body-parser');

var app = express();

// parse application/x-www-form-urlencoded
**app.use(bodyParser.json());**
app.use(bodyParser.urlencoded({ extended: false }));

Upvotes: 1

Laurent Perrin
Laurent Perrin

Reputation: 14881

You got Content-Length: 0, so the problem is on the client side. Your Express code looks OK.

Upvotes: 4

Related Questions