在nodejs中转发代理
我用nodejs做了一个小的转发代理,并把它放在appfog中。 它设置了我的浏览器的代理后在本地工作,但是当我尝试使用托pipe在appfog中的一个说:* Errore 130(net :: ERR_PROXY_CONNECTION_FAILED):Connessione al服务器代理非riuscita。*这是我的代码:
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 …本地工作,但是当我使用远程地址作为代理它不
首先:应用程序需要使用cloudfoundry发布的端口号。 该应用程序位于反向代理后面,该端口接收端口80上的传入请求并将它们转发给VCAP_APP_PORT。
var port = process.env.VCAP_APP_PORT || 8080; // 8080 only works on localhost .... }).listen(port);
然后你访问你的托pipe应用程序,像这样:
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上testing了下面的代码,这些IP是不同的。 Whatismyip在本地运行时返回了本地interent ip地址,并且在AppFog托pipe的应用程序上返回了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);