代理服务器后面的nodejs的简单示例

下面是一个简单的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 )。 仍然想知道如何用香草节点库做到这一点。

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

通常最好在系统级别处理代理 – 将操作系统configuration为使用代理而不是脚本。 然而这也可能会失败,因为大多数企业代理没有打开所有的端口。

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

在这一点上,你可以将你所有的本地networking通信隧道到服务器,或SSH到服务器,并在那里运行脚本。

如果您要使脚本代理具体化,那么它们不会非常便于携带,而且不会因为代理configuration发生变化而中断生产。