Travis Parks Travis Parks - 4 months ago 41
Node.js Question

HTTP GET Request in Node.js Express

How can I make an HTTP request from within node/express? I need to connect to another service. I am hoping the call is async and that the callback contains the remote servers response.

Answer

Here's code from a sample of mine. It's async and returns a JSON object. It could do any get request. Note there's more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:

var http = require("http");
var https = require("https");

/**
 * getJSON:  REST get request returning JSON object(s)
 * @param options: http options object
 * @param callback: callback to pass the results JSON object(s) back
 */
exports.getJSON = function(options, onResult)
{
    console.log("rest::getJSON");

    var prot = options.port == 443 ? https : http;
    var req = prot.request(options, function(res)
    {
        var output = '';
        console.log(options.host + ':' + res.statusCode);
        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            output += chunk;
        });

        res.on('end', function() {
            var obj = JSON.parse(output);
            onResult(res.statusCode, obj);
        });
    });

    req.on('error', function(err) {
        //res.send('error: ' + err.message);
    });

    req.end();
};

It's called by creating an options objects like:

var options = {
    host: 'somesite.com',
    port: 443,
    path: '/some/path',
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
};

and providing a callback function.

For example, in a service, I require the rest module above and then do this.

    rest.getJSON(options,
        function(statusCode, result)
        {
            // I could work with the result html/json here.  I could also just return it
            console.log("onResult: (" + statusCode + ")" + JSON.stringify(result));
            res.statusCode = statusCode;
            res.send(result);
        });

I have a more complete sample if you're interested.

UPDATE:

Here is the more complete integrated sample: https://github.com/bryanmacfarlane/nodefun

Look in /express/helloworld

It's a sample where node.js is using parse.com as a back so it sends REST requests over http. To get it to work, you need the parse.com app id/key in /service/secrets.js