0

I'm a complete beginner in Node.js and I wanted to consult something I could not figure out.

Even though I've researched extensively I could not find any method to receive JSON request without using a plugin. I will be using it to program a mobile application API. But even though I've incluede parameter request I cannot reach the content by using request.body, or request.data. The request I'm trying to make is;

{
    "id":"123"
}

And my failing code is;

var http = require('http');

function onRequest(request, response){
    console.log("Request: "+request.data+"\n");
    response.writeHead(200, {"Content-Type":"text/plain"});
    response.write("Hello, World");
    response.end();
}

http.createServer(onRequest).listen(8888);
Ali
  • 5,338
  • 12
  • 55
  • 78
  • http://stackoverflow.com/questions/9577611/http-get-request-in-node-js-express/9577651#9577651 – bryanmac Sep 30 '12 at 17:02
  • @bryanmac Thanks for the answer. However in your code I could not understand where the "exports" parameter came from? – Ali Sep 30 '12 at 17:26
  • I'd recommend you to use express, as in this question http://stackoverflow.com/questions/4295782/node-js-extracting-post-data – Herman Junge Sep 30 '12 at 18:23

1 Answers1

1

The problem here is that you're not listening to the request events to let you know that you have data, and then parsing the data. You're assuming that request has request.data.

It should be:

var http = require('http');

function onRequest(request, response){
  var data = '';
  request.setEncoding('utf8');

  // Request received data.
  request.on('data', function(chunk) {
    data += chunk;
  });

  // The end of the request was reached. Handle the data now.
  request.on('end', function() {
    console.log("Request: "+data+"\n");
    response.writeHead(200, {"Content-Type":"text/plain"});
    response.write("Hello, World");
    response.end();
  });
}

http.createServer(onRequest).listen(8888);

See this for the documentation for the methods that request contains.

Sly
  • 1,145
  • 7
  • 19