我需要创建应用程序来获取特定端口的请求并将其代理到不同端口上的新服务器
例如以下端口 3000 将代理到端口 9000 并且您实际上在 9000 上运行应用程序(在后台),因为客户端中的用户单击 3000
我尝试类似的事情
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 () {
});
- 这样做的方法正确吗?
- 如何测试它?我问,因为如果我在端口 3000 中运行 Node 应用程序,我无法将第一个 URL 放入客户端 http://localhost:3000/a/b/c因为该端口已被占用。有解决办法吗?
最佳答案
很少examples关于代理服务器的各种使用。这是基本代理服务器的简单示例:
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);
测试代理服务器是否正常工作或者请求是否来自代理服务器:
我添加了一个 proxyReq
监听器,它添加了自定义 header 。您可以从该 header 判断请求是否来自代理服务器。
因此,如果您访问 http://localhost:8080/a/b/c
,您会看到 req.headers
有一个如下所示的 header :
'X-Special-Proxy-Header': 'foobar'
仅当客户端向 8080 端口发出请求时才会设置此 header
但是对于http://localhost:3000/a/b/c
,您不会看到这样的 header ,因为客户端绕过代理服务器并且该 header 从未设置。
关于javascript - 检查新端口上运行的应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31254175/