Tuesday, January 25, 2011

Posting data with Node.js

Recently i needed to post data using node.js, I was not trying to post a long string of data but rather parameters from a form. But the Node.js help page isn't too helpful, it just say use request.write() to write data to the stream

  This is the first interation i got.

 

var http=require('http'); var post=http.createClient(80,'localhost'); var request=post.request('POST',/test.php'.{'host':'localhost'}); request.write('test=10'); request.end(); request.on('response',function(response){ response.setEncoding('utf8'); reponse.on('data',function(chunk){ console.log(chunk); } });
 
test.php is a simple php script that prints out the parameter value.

  I got nothing... nothing was printed out. What was wrong?

  Using curl and Fiddler, i did a little investigating about what went wrong, what was missing was the Content-Length and the Content-Type which needs to be application/x-www-form-urlencoded.

  Adding these 2 parameters to the script

var http=require('http'); var post=http.createClient(80,'localhost'); var request=post.request('POST',/test.php'.{'host':'localhost','Content-Length':'7','Content-Type':'application/x-www-form-urlencoded'}); request.write('test=10'); request.end(); request.on('response',function(response){ response.setEncoding('utf8'); reponse.on('data',function(chunk){ console.log(chunk); } });
 
And yeah ! It works !