【问题标题】:Check app running on new port检查在新端口上运行的应用程序
【发布时间】:2015-07-06 19:36:09
【问题描述】:

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

例如以下端口 3000 将代理到端口 9000 并且您实际上在 9000 上运行应用程序(在后台),因为客户端中的用户单击 3000

http://localhost:3000/a/b/c

http://localhost: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. 如何对其进行测试?我问,如果我在端口 3000 中运行节点应用程序,我不能将第一个 URL 放在客户端 http://localhost:3000/a/b/c 中,因为这个端口已经被占用。有解决办法吗?

【问题讨论】:

    标签: javascript node.js express node-http-proxy node-request


    【解决方案1】:

    关于代理服务器的各种用法,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 监听器,它添加了一个自定义标头。您可以从此标头中判断请求是否来自代理服务器。

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

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

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

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

    【讨论】:

    • 感谢投票!但我应该如何测试它,你能解释一下吗?
    • 感谢哈萨辛!投票赞成!最后一个问题是,现在我有了手动切换到新代理端口所需的新服务器,我应该如何在后台将调用导航到新端口?
    • 在上面的例子中,只需将 8080 替换为 3000,将 3000 替换为 9000
    • 谢谢,但是当我点击 localhost:3000 时,我进入了 json "host": "localhost:3000",我不需要得到 9000?
    • 我明白了。您可以设置proxyReq.setHeader('host','localhost:9000') - 但可能有更好的方法。我会调查的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2019-05-27
    • 2011-07-04
    • 2020-01-26
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    相关资源
    最近更新 更多