Travis Parks Travis Parks - 1 year ago 135
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 Source

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)

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

        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);


It's called by creating an options objects like:

var options = {
    host: '',
    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.

        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;

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


Here is the more complete integrated sample:

Look in /express/helloworld

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