代理后面的nodejs的简单示例

时间:2013-01-29 16:10:32

标签: node.js https proxy

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

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

1 个答案:

答案 0 :(得分:1)

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

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

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

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

相关问题