Monday, July 7, 2014

NodeJs: Call API through proxy

How to call an API inside NodeJs through a proxy?

I came across a problem where our box (vagrant box) was configured in a way that we could not call any site (website or API) directly, we have to use our proxy.

So the solution I found was to use a tunnel npm module.

Below is a mocha test I created to test calling an API through a proxy:
var tunnel = require('tunnel');
var https = require('https');
var url = require('url');

describe('call api through proxy', function () {
    it('should be able to access http', function (done) {
        var inputToken = 'YOUR_INPUT_TOKEN'; // this should be from config/redis
        var accessToken = 'ACCESS_TOKEN';

        var urlParsed = url.parse(process.env.https_proxy); // get the proxy

// declare the tunnel
        var tunnelingAgent = tunnel.httpsOverHttp({
            proxy: {
                host: urlParsed.hostname,
                port: urlParsed.port
            }
        });

// FB option
        var options = {
            host: "graph.facebook.com",
            port: 443,
            path: '/debug_token?input_token=' + inputToken + '&access_token=' + accessToken,
            agent: tunnelingAgent,

        };
        var reqGet = https.get(options, function (res) {
            var chunk = '';
            res.on('data', function (d) {
                console.info('GET result:\n');
                chunk += d;
                process.stdout.write(d);
            });
            res.on('end', function () {
                var fbResponse = JSON.parse(chunk);
                console.log("Got response: ", fbResponse);
                done();
            });
        });

        reqGet.end();
        reqGet.on('error', function (e) {
            console.error(e);
        });
    });
});

Hope this helps!


No comments:

Post a Comment