mishkovski
2/25/2015 - 6:56 PM

Helper function for HTTP requests in Node.js

Helper function for HTTP requests in Node.js

var http = require('http');

function makeRequest(method, host, port, path, queryString, body, handler) {    
    var options = {
        method: method,
        host: host,
        port: port,
        path: path + queryString,
        headers: {
            'Content-Type': 'application/json',
        }
    };
    
    var postData = "";
    if (body) {
        if (typeof body === "string") {
            postData = body;
        }
        else {
            postData = JSON.stringify(body);
        }       
        if (postData) {
            options.headers["Content-Length"] = postData.length;
        }
    }

    var req = http.request(options, function (response) {
        response.setEncoding('utf-8');
        var str = '';
        response.on('data', function (chunk) {
            str += chunk;
        });
        response.on('end', function () {
            // Assume JSON response if any
            var result = null;
            if (str)
                result = JSON.parse(str);
            handler(null, result);
        });
    });

    req.on('error', function (e) {
        if (handler)
            handler(e, undefined);
    });

    // write data to request body if any
    if (body) {
        req.write(postData);
    }

    req.end();
}