Send GET and POST requests in Node.js
posted on August 11, 2014, 12:24 am in
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);
});