code everywhere

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(ip, port, path, cb) {
    var 
options = {
       
host: ip,
       
port: port,
       
path: path,
       
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() { cb( result ); });
    });
    
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(ip, port, path, data, cb ) {

    var 
options = {
       
host: ip,
       
port: port,
       
path: path,
       
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() { cb( result ); });
    });
    
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
find something helpful? send us some coin BTC 19u6CWTxH4cH9V2yTfAemA7gmmh7rANgiv

(ad) Need Hosting? Try Linode, VPS Starting from $5

privacy policy