0

I used to parse post request body with express.js, but now it started to give undefined when i try to log req.body.gsm. {"gsm":"10"} this is my post data, and I make the request with a rest client.

   app.configure(function(){
      app.use(express.bodyParser());
      app.use(app.router);
      app.use(express.static(__dirname + '/public'));
    });

  app.post('/gsm', function (req, res) {

  var gsm = req.body.gsm; //gsm is undefined when i log

  var body = req.body;  //this is the log of body { '{\n"gsm":"10"\n}': '' }

  });
  • It looks like the problem is not in the nodejs part, but in the client-side code. I.e. the place where you submit the data. Can you please post that script. – Krasimir Dec 06 '13 at 14:07
  • i am using cocoaRestClient and this is the data i post: {"gsm":"10"} –  Dec 06 '13 at 14:08
  • I wanted to see the actual code which sends the data. Probably you send the data as a string. So, if you use JSON.stringify before to pass the data to the cocoaRestClient, remove it. – Krasimir Dec 06 '13 at 14:30

1 Answers1

1

Looks like you're receiving the body as a string, not a JSON object. Express will parse the body into a full JSON object only if the Content-type: application/json header is set, see the source code of connect's json middleware.

Just send the same request with the Content-type: application/json header.

Sample curl script to test this:

$ curl -XPOST -H "Content-type: application/json" -d '{"gsm":"10"}' "http://localhost/gsm"
Paul Mougel
  • 16,728
  • 6
  • 57
  • 64