2012-11-22 42 views
3

我用nodejs製作了一個小型轉發代理,並將其託管在appfog中。 設置我的瀏覽器的代理後它在本地工作,但是當我嘗試使用託管在appfog中的一個: * Errore 130(net :: ERR_PROXY_CONNECTION_FAILED):Connessione al server proxy non riuscita。* 這是我的代碼:nodejs中的轉發代理

var http = require('http'); 
http.createServer(function(request, response) { 
http.get(request.url, function(res) { 
    console.log("Got response: " + res.statusCode); 
    res.on('data', function(d) { 
     response.write(d); 
    }); 
    res.on('end', function() { 
    response.end(); 
    }); 
}).on('error', function(e) { 
    console.log("Got error: " + e.message); 
}); 
}).listen(8080); 

我錯過了什麼嗎?

你的代碼工作,但一旦我使用它像這樣嘗試:

var port = process.env.VCAP_APP_PORT || 8080; 
var http = require('http'); 
var urldec = require('url'); 
http.createServer(function(request, response) { 
var gotourl=urldec.parse(request.url); 
var hosturl=gotourl.host; 
var pathurl=gotourl.path; 
var options = { 
    host: hosturl, 
    port: 80, 
    path: pathurl, 
    method: request.method 
    }; 

    http.get(options, function(res) { 
    console.log("Got response: " + res.statusCode); 
    res.on('data', function(d) { 
     response.write(d); 
    }); 
    res.on('end', function() { 
     response.end(); 
    }); 
    }).on('error', function(e) { 
    console.log("Got error: " + e.message); 
    response.write("error"); 
    response.end(); 
    }); 
}).listen(port); 
console.log(port); 

它仍然不能正常工作:我得到請求超時,當我嘗試ping地址,我得到了相同的ERR_PROXY_CONNECTION_FAILED ......在本地工作,但在使用遠程地址作爲代理我它不

回答

2

第一:的應用程序需要使用由cloudfoundry發給它的端口號。該應用程序位於反向代理的後面,該代理將端口80上的傳入請求轉發給VCAP_APP_PORT。

var port = process.env.VCAP_APP_PORT || 8080; // 8080 only works on localhost 

.... 

}).listen(port); 

然後您訪問託管應用程序是這樣的:

http://<app_name>.<infra>.af.cm // port 80 

而且本地應用程序:

http://localhost:8080 

二:您可能需要使用一個選項哈希發送到http.get方法,而不是隻提供request.url。

var options = { 
    host: '<host part of url without the protocal prefix>', 
    path: '<path part of url>' 
    port: 80, 
    method: 'GET' } 

我測試了我的本地盒和AppFog下面的代碼和IP地址是不同的。 Whatismyip在本地運行時返回本地interent ip地址,並在AppFog託管的應用程序上返回AppFog服務器ip。

var port = process.env.VCAP_APP_PORT || 8080; 
var http = require('http'); 
var options = { 
    host: "www.whatismyip.com", 
    port: 80, 
    path: '/', 
    method: 'GET' 
    }; 
http.createServer(function(request, response) { 
    http.get(options, function(res) { 
    console.log("Got response: " + res.statusCode); 
    res.on('data', function(d) { 
     response.write(d); 
    }); 
    res.on('end', function() { 
     response.end(); 
    }); 
    }).on('error', function(e) { 
    console.log("Got error: " + e.message); 
    response.write("error"); 
    response.end(); 
    }); 
}).listen(port); 
+0

嗨,感謝您的答案,但我已經嘗試過,當我去一個網站,當我可以測試我的IP,我得到了相同的IP和無需使用代理..我正在做一個新的在服務器上的http請求,所以我也看到服務器IP,不是我的是對的? – MkM

+0

請參閱我的答案編輯的第二部分。 –

+0

我試着用你的代碼使用動態url,但它不起作用,你能再次看到我的消息...謝謝 – MkM