3

I am new to node JS. I am getting undefined for post request. My express version is 4.10. I think I am missing something.

var express = require('express');
var http = require('http');

var app = express();

app.use(express.static(__dirname + '/public'));

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

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.post('/test',function(req,res){
    var color1 = req.body.color;   
    console.log(req.headers);
    console.log("Color : "+color1);
});

In content-length I am getting 234. enter image description here Thanks!!

Rahul
  • 314
  • 5
  • 12
  • 1
    How are you POSTing to the server? What does the `console.log(req.headers);` show (especially the `Content-Type`)? I'm guessing it's `multipart/form-data`, which the `body-parser` module does not support. – mscdex Jan 08 '15 at 20:04
  • I am using POSTMAN for posting to server. – Rahul Jan 08 '15 at 20:08
  • To support multipart/form-data, which module should I suppose to use? – Rahul Jan 08 '15 at 20:13
  • @mscdex Thanks!! Above code is working when I set content-type = "application/json" – Rahul Jan 08 '15 at 21:04

3 Answers3

6

For future visitors - it seems that @mscdex's suggestion lead @Rahul to change the client calling his API so that it passed application/json as the value for the Content-Type header. Another option is to change the Content-Type header that body-parser attempts to parse.

You can configure body-parser to accept a different Content-Type by specifying the type it accepts as follows:

app.use(bodyParser.json({ type: 'application/vnd.api+json' }));

This is the solution that worked for me in order to parse the JSON sent from an Ember app. I felt it was better to change the default Content-Type header accepted by body-parser than changing the rest of the tooling around my application.

Oren Hizkiya
  • 4,420
  • 2
  • 23
  • 33
0

The correct answer is to change the default Content-Type as described above:

app.use(bodyParser.json({
    type: 'application/vnd.api+json',
    strict: false
}));

strict:false gets around some bugs in bodyParser rejecting valid JSON objects.

Varun Agarwal
  • 1,587
  • 14
  • 29
0

npm install body-parser

However, if you are running a version of Express that is 4.16+, it now includes the same functionality inside of Express.

Instead of adding these lines in the code to get req.body:

app.use(bodyparser.urlencoded({extended: false}));
app.use(bodyparser.json());

If you are using Express 4.16+ you can now replace that with:

app.use(express.urlencoded({extended: false}));
app.use(express.json());