Sunday, February 13, 2011

NodeJS - HTTP Request

1. GET

 var http = require('http');  
// GET.
var options = {
host: 'localhost',
port: 3000,
path: '/user/suwanny'
};
var req = http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
res.on('data', function(chunk) {
console.log("Body: " + chunk);
});
}).on('error', function(e) {
console.log("Got error: " + e.message);
});


2. POST

 // POST.   
var http = require('http');
var options = {
host: 'localhost',
port: 3000,
path: '/load/debug',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log("Got response: " + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.on('data', function(chunk) {
console.log("Body: \n" + chunk);
});
});
req.end();

3 comments:

Владимир Градев said...

10x a lot! It's clean and simple !

Unknown said...

Thanks a lot, your blog illustrates it very simple. But this when I make a POST or Get request from NodeJS.

Can I create a server handler that accepts a POST request, and then do some task?

Unknown said...

You can also use Requestify which is a great simple module that also supports caching.

http://ranm8.github.io/requestify