2013-05-08 48 views
6

我最近創建了一個node.js應用程序,它可以連接到社交媒體網站並緩存我們的公共提要。我正在使用一些現有的npm模塊來方便訪問社交媒體API。它在我的開發環境中像一個魅力一樣工作,但在我們的生產環境中,請求已超時,因爲它們需要通過代理。如何覆蓋node.js http對所有出站請求使用代理

無需修改npm模塊如何使出站請求通過代理?

回答

3

使用http.globalAgent屬性。這將允許您攔截在您的流程中運行的所有請求。然後,您可以修改這些請求,以便爲代理服務器正確格式化。

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

另一種選擇是創建該應用程序的代理例外。

+3

可能喲你給我一個使用http.globalAgent的例子,我可以通過'{host:'http.proxy.somewhere.com',port:1234,path:'http://www.google.com'}'作爲選項和適用於我自己的請求,但我已經嘗試'http.globalAgent.options = {主機:'http.proxy.somewhere.com',端口:1234};'我的公司代理是http:// http .proxy.somewhere.com:1234'並且不起作用 – jonnie 2013-12-11 15:58:35

+1

是的,請提供一個通過globalAgent代理路由所有出站請求的示例。 – 2014-04-03 18:55:11

2

有針對的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 
});