20

I send a POST WebRequest from C# along with a JSON object data and want to receive it in a Node.js server like this:

var express = require('express');
var app = express.createServer();

app.configure(function(){
  app.use(express.bodyParser());
});
app.post('/ReceiveJSON', function(req, res){
  //Suppose I sent this data: {"a":2,"b":3}

  //Now how to extract this data from req here?  

  //console.log("req a:"+req.body.a);//outputs 'undefined'
  //console.log("req body:"+req.body);//outputs '[object object]'


  res.send("ok");
});

app.listen(3000);
console.log('listening to http://localhost:3000');      

Also, the C# end of POST WebRequest is invoked via the following method:

public string TestPOSTWebRequest(string url,object data)
{
    try
    {
        string reponseData = string.Empty;

        var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.Method = "POST";
            webRequest.ServicePoint.Expect100Continue = false;
            webRequest.Timeout = 20000;

            webRequest.ContentType = "application/json; charset=utf-8";
            DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType());
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, data);
            String json = Encoding.UTF8.GetString(ms.ToArray());
            StreamWriter writer = new StreamWriter(webRequest.GetRequestStream());
            writer.Write(json);
        }

        var resp = (HttpWebResponse)webRequest.GetResponse();
        Stream resStream = resp.GetResponseStream();
        StreamReader reader = new StreamReader(resStream);
        reponseData = reader.ReadToEnd();

        return reponseData;
    }
    catch (Exception x)
    {
        throw x;
    }
}

Method Invocation:

TestPOSTWebRequest("http://localhost:3000/ReceiveJSON", new TestJSONType {a = 2, b = 3});  

How can I parse JSON data from request object in Node.js code above?

hong4rc
  • 3,334
  • 2
  • 16
  • 36
zee
  • 211
  • 1
  • 3
  • 8

2 Answers2

33

The request has to be sent with: content-type: "application/json; charset=utf-8"

Otherwise the bodyParser kicks your object as a key in another object :)

faeb187
  • 459
  • 5
  • 7
22

bodyParser does that automatically for you, just do console.log(req.body)

Edit: Your code is wrong because you first include app.router(), before the bodyParser and everything else. That's bad. You shouldn't even include app.router(), Express does that automatically for you. Here's how you code should look like:

var express = require('express');
var app = express.createServer();

app.configure(function(){
  app.use(express.bodyParser());
});

app.post('/ReceiveJSON', function(req, res){
  console.log(req.body);
  res.send("ok");
});

app.listen(3000);
console.log('listening to http://localhost:3000');

You can test this using Mikeal's nice Request module, by sending a POST request with those params:

var request = require('request');
request.post({
  url: 'http://localhost:3000/ReceiveJSON',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    a: 1,
    b: 2,
    c: 3
  })
}, function(error, response, body){
  console.log(body);
});

Update: use body-parser for express 4+.

alessioalex
  • 57,958
  • 15
  • 152
  • 119
  • 1
    console.log(req.body) outputs [object object]; I tried req.body.a too but it prints undefined. – zee Jan 05 '12 at 13:27
  • I've edited my code, your error was putting router before every other middleware (including bodyParser). – alessioalex Jan 05 '12 at 13:36
  • hmmm. but now console.log(req.body); outputs {}! how to extract json object properties a & b? – zee Jan 05 '12 at 13:45
  • if you run my exact code everything works ok, I've even tested locally :) – alessioalex Jan 05 '12 at 13:49
  • I have ur exact code bro.Shall I also show u C# webrequest? although it does show {"a":2,"b":3} being passed on debugging. – zee Jan 05 '12 at 13:56
  • Then your C# webrequest is causing problems. See my updated response, I've included a post request to test this out. – alessioalex Jan 05 '12 at 14:12
  • Ok. At lease your client & server code test is as expected. Now it must be my WebRequest end fault. I will try to find out what! – zee Jan 05 '12 at 14:33
  • Maybe there's a problem with our version of express? I also can't seem to make a POST request. Even when copying @alessioalex's answer. I'm using node v0.6.6, express 2.5.4 and jQuery 1.7 with $.ajax – idophir Jan 05 '12 at 16:35
  • I also get {} as the value of req.body. – Sam Jun 26 '13 at 08:33
  • Wanted to add, app.configure is not needed in express 4+ – Jose A Jun 02 '17 at 00:48