Node.js and receiving POST-data from HTTP

I have built an application that needed to communicate with another Linux server. It was very simple commands that my nodeserver should receive.

To get the POST-variables in the in-built HTTP-server from NodeJS you can use this method:

function onRequest(request, response) {
  var pathname = url.parse(request.url).pathname;
  console.log("Request for " + pathname + " received.");
  response.writeHead(200, {"Content-Type": "text/plain"});
 
  post_handler(request, function(request_data)
   {
	console.log(sys.inspect(request_data));
	response.end();
   });
}
function post_handler(request, callback)
{
    var _REQUEST = { };
    var _CONTENT = '';
 
    if (request.method == 'POST')
    {
        request.addListener('data', function(chunk)
	{
	    _CONTENT+= chunk;
	});
 
	request.addListener('end', function()
	{
        _REQUEST = querystring.parse(_CONTENT);
	    callback(_REQUEST);
	});
    };
};
 
http.createServer(onRequest).listen(8888);

Tags: , , ,

Leave a Reply