quickshiftin quickshiftin -3 years ago 78
Node.js Question

Node https request options within response callback

I'm making an https request with the node

module wherein I set the
localAddress
option
. Each local IP in the list is mapped to a different public IP.

I'm simply trying to print the public IP as reported by a server on the internet beside the corresponding local IP. The problem is I'm not sure how to get the request options in the response callback:

var https = require('https');

var localIps = [
'192.168.88.135',
'192.168.88.136',
'192.168.88.137',
'192.168.88.138',
'192.168.88.139',
];

for(index in localIps) {
var localIp = localIps[index];

var options = {
localAddress: localIp,
host: 'mypublicserver.com',
path: '/whats-my-ip.php'
};

https.get(options, function(res) {
res.on('data', function(d) {
console.log(
// XXX localIp is always printing the last IP from localIps
'Local Network IP: ' + localIp +
' Public Outbound IP: ' + d);
});

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


It's printing something like this (which is wrong)

Local Network IP: 192.168.88.139 Public Outbound IP: 88.88.888.132
Local Network IP: 192.168.88.139 Public Outbound IP: 88.88.888.131
Local Network IP: 192.168.88.139 Public Outbound IP: 88.88.888.130
Local Network IP: 192.168.88.139 Public Outbound IP: 88.88.888.133
Local Network IP: 192.168.88.139 Public Outbound IP: 88.88.888.134


So how do I get the correct options object inside the response callback?

Apparently
res
is an
http.IncomingMessage
instance
, but I'm failing to find how to get the associated request object from it.

Answer Source

The problem is that the for loop will finish iterating over localIps before any of the responses comes back. So when the first response comes back the localIp variable is set to last ip of the localIps array.

The easiest you can do is to enclose the code in closure or also called IIFE -> Immediately invoked function expression

var https = require('https');

var localIps = [
    '192.168.88.135',
    '192.168.88.136',
    '192.168.88.137',
    '192.168.88.138',
    '192.168.88.139',
];

for(index in localIps) {
    var localIp = localIps[index];

    var options = {
        localAddress: localIp,
        host: 'mypublicserver.com',
        path: '/whats-my-ip.php'
    };

    (function(opts){

        https.get(opts, function(res) {
            res.on('data', function(d) {
                console.log(
                    // XXX localIp is always printing the last IP from localIps
                    'Local Network IP: ' + opts.localAddress +
                    ' Public Outbound IP: ' + d);
            });

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

    })(options);
}

To find more https://www.google.cz/search?q=javascript+for+loop+closure

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download