code everywhere
technology, web services and applications

Send GET and POST requests in Node.js

posted on August 11, 2014, 12:24 am in js, nodejs

Node.js is often used as a middleware server to make requests to other servers via GET / POST. There are lots of frameworks that solve this problem, but sometimes you want to keep it simple, so with no external dependancies.

Simple GET Function

var http = require('http');

var 
HTTPGetReq = function(ipportpathcb) {
    var 
options = {
       
hostip,
       
portport,
       
pathpath,
       
method"GET",
       
headers: { "Content-Type""application/json" }
    };
    var 
req http.request(options, function(res) {
        var 
result '';
        
res.on('data', function(chunk) { result += chunk; });
        
res.on('end', function() { cbresult ); });
    });
    
req.on('error', function(err) { console.log(err); });
    
req.end();
};

Example usage:

HTTPGetReq("0.0.0.0"80"/path/to/api", function(res) {
    
console.log("result="res);
});

Simple POST Function

var HTTPPostReq = function(ipportpathdatacb ) {

    var 
options = {
       
hostip,
       
portport,
       
pathpath,
       
method"POST",
       
headers: {
           
"Content-Type""application/json",
           
"Content-Length"Buffer.byteLength(data)
        }
    };
    
    var 
req http.request(options, function(res) {
        var 
result '';
        
res.on('data', function(chunk) { result += chunk; });
        
res.on('end', function() { cbresult ); });
    });
    
req.on('error', function(err) { console.log(err); });
    
req.write(data);
    
req.end();
};

Example usage:

HTTPPostReq("0.0.0.0"80"/path/to/api"data, function(res) {
    
console.log("result="res);
});

recent posts

< back