4

这是一个简单的 nodejs 脚本,用于使用 node 作为 https 客户端与外界交互。如何修改它,以便在像这样的公司代理后面运行它时不会出现“ECONNREFUSED”错误http://10.10.10.10:8080

var https = require('https');

var options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET'
};

var req = https.request(options, function(res) {
  console.log("statusCode: ", res.statusCode);
  console.log("headers: ", res.headers);

  res.on('data', function(d) {
    process.stdout.write(d);
  });
});
req.end();

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

- - 更新 - -

我想出了如何使用 npm 'request' 包(https://github.com/mikeal/request)。仍然想知道如何使用 vanilla 节点库来做到这一点。

var request = require('request').defaults({proxy:'http://my.proxy.server:8080', agent:false});
request('https://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Print the google web page.
  }
})
4

1 回答 1

1

通常最好在系统级别处理代理 - 将您的操作系统配置为使用代理而不是脚本。但是,这也可能会失败,因为大多数公司代理并没有打开所有端口。

一个通用的解决方案是让服务器(EC2 或 Rackspace 实例)充当您自己的代理,并让它在端口 443 上侦听 ssh。端口 443 在公司防火墙中为 https 开放。

此时,您可以将所有本地网络流量通过隧道传输到服务器,或者通过 ssh 连接到服务器并在那里运行脚本。

如果您要使脚本代理特定,它们将不是非常便携,并且不会在生产环境中强化,因为它们会在代理配置更改时中断。

于 2014-08-05T21:34:38.970 回答