Check app running on new port

你说的曾经没有我的故事 提交于 2019-12-11 03:26:48

问题


I need to create application which get request for specific port and proxy it to new server on different port

for example the following port 3000 will be proxy to port 9000 and you actually run the application on 9000 ( under the hood) since the user in the client click on 3000

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

http://localhost:9000/a/b/c

I try something like

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. Is the right way to do it?
  2. How can I test it? I ask since if I run the node application in port 3000 I cannot put the first URL in the client http://localhost:3000/a/b/c since this port is already taken. Is there a workaround?

回答1:


There are few examples on various usage of proxy server. Here is a simple example of a basic proxy server:

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);

To Test if the proxy server working or if the request is coming from proxy server:

I've added a proxyReq listener which adds a custom header. You can tell from this header if the request came from the proxy server.

So, if you visit http://localhost:8080/a/b/c you'll see the req.headers has a header like this:

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

This header is set only when client makes a request to 8080 port

But for http://localhost:3000/a/b/c, you won't see such header because client is bypassing the proxy server and that header is never set.



来源:https://stackoverflow.com/questions/31254175/check-app-running-on-new-port

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!