响应回调中的节点https请求选项

时间:2017-06-13 14:18:58

标签: node.js https

我正在使用节点https module发出https请求,其中我设置了localAddress option。列表中的每个本地IP都映射到不同的公共IP。

我只是尝试打印互联网上的服务器在相应的本地IP旁边报告的公共IP。问题是我不知道如何在响应回调中获取请求选项:

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

它正在打印这样的东西(这是错误的)

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

那么如何在响应回调中获取正确的选项对象?

显然reshttp.IncomingMessage instance,但我找不到如何从中获取相关的请求对象。

1 个答案:

答案 0 :(得分:1)

问题是for循环将在任何响应返回之前完成对localIps的迭代。因此,当第一个响应返回时,localIp变量被设置为localIps数组的最后一个ip。

最简单的方法是将代码封闭在封闭中,也称为IIFE代码 - >立即调用函数表达式

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

要查找更多https://www.google.cz/search?q=javascript+for+loop+closure