如何覆盖node.js http为所有出站请求使用代理

我最近创build了一个node.js应用程序,用于联系社交媒体网站并caching我们的公共提要。 我正在使用一些现有的npm模块来方便访问社交媒体API。 它在我的开发环境中像一个魅力,但是在我们的生产环境中,请求会因为需要通过代理而超时。

无需修改npm模块,我怎样才能使出站请求通过代理?

使用http.globalAgent属性。 这将允许您拦截在您的stream程中运行的所有请求。 然后,您可以修改这些请求以正确格式化代理服务器。

http://nodejs.org/api/http.html#http_http_globalagent

另一种select是为该应用程序创build代理例外。

有一个npm模块:

https://www.npmjs.com/package/global-tunnel

 var globalTunnel = require('global-tunnel'); globalTunnel.initialize({ host: '10.0.0.10', port: 8080, sockets: 50 // optional pool size for each http and https }); 

或者,如果您只想代理某些请求,则可以使用隧道包(这是上述全局隧道背后的驱动力):

https://www.npmjs.com/package/tunnel

 var tunnel = require('tunnel'); // create the agent var tunnelingAgent = tunnel.httpsOverHttps({ proxy: { host: 'localhost', port: 3128 } }); var req = https.request({ host: 'example.com', port: 443, // pass the agent in your request options agent: tunnelingAgent });