检查在新端口上运行的应用程序

我需要创build应用程序获取特定端口的请求,并将其代理到不同端口上的新服务器

例如下面的端口3000将代理端口9000,你实际上运行在9000(应用程序引擎)的应用程序,因为客户端中的用户点击3000

HTTP://本地主机:3000 / A / B / C

HTTP://本地主机:9000 / A / B / C

我尝试类似

var proxy = httpProxy.createProxyServer({}); http.createServer(function (req, res) { var hostname = req.headers.host.split(":")[0]; var pathname = url.parse(req.url).pathname; proxy.web(req, res, { target: 'http://' + hostname + ':' + 9000 }); var proxyServer = http.createServer(function (req, res) { res.end("Request received on " + 9000); }); proxyServer.listen(9000); }).listen(3000, function () { }); 
  1. 是正确的方法来做到这一点?
  2. 我如何testing它 ? 我问,因为如果我在端口3000运行节点应用程序我不能把第一个URL放在客户端http:// localhost:3000 / a / b / c,因为这个端口已经被采取。 有没有解决方法?

代理服务器的各种使用方法很less。 这是一个简单的代理服务器的例子:

 var http = require("http"); var httpProxy = require('http-proxy'); /** PROXY SERVER **/ var proxy = httpProxy.createServer({ target:'http://localhost:'+3000, changeOrigin: true }) // add custom header by the proxy server proxy.on('proxyReq', function(proxyReq, req, res, options) { proxyReq.setHeader('X-Special-Proxy-Header', 'foobar'); }); proxy.listen(8080); /** TARGET HTTP SERVER **/ http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); //check if the request came from proxy server if(req.headers['x-special-proxy-header']) console.log('Request received from proxy server.') res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2)); res.end(); }).listen(3000); 

testing代理服务器是否工作或者请求是否来自代理服务器:

我已经添加了一个proxyReq监听器,它添加了一个自定义标题。 如果请求来自代理服务器,您可以从此标头中得知。

所以,如果你访问http://localhost:8080/a/b/c你会看到req.headers有这样的头文件:

 'X-Special-Proxy-Header': 'foobar' 

仅当客户端向8080端口发出请求时才设置此标头

但是对于http://localhost:3000/a/b/c ,您将看不到这样的标头,因为客户端正在绕过代理服务器,并且该标头从不设置。