Proxy request to new port with http-proxy

I am using this code. I want to create a proxy so that all application calls on port 3000 are redirected "under the hood" to port 3002

var http = require('http'), httpProxy = require('http-proxy'); var proxy = httpProxy.createProxyServer(); http.createServer(function (req, res) { proxy.web(req, res, { target: 'http://localhost:3002' }); }).listen(3000); // Create target server http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2)); res.end(); }).listen(3002); 

Now, when I launch the application with the source port (3000), I see in the browser

request is successfully proxied to 3002

  • When I change the port (in the browser) to 3002 , I still get the same message, why? this is normal?

  • What should I add to production inside the second server? I mean instead

     res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2)); res.end(); 
  • Should there be res.end() ?

I am using the code from https://github.com/nodejitsu/node-http-proxy

+6
source share
2 answers

When I change the port (in the browser) to 3002, I still get the same message, why? this is normal?

It's fine. You have set up a "real" server listening on port 3002. If you try to access it directly, there is no reason for this not to work, and what the event handler of your request (on this server) does, returns the string "request successfully proxied to:" + url. Nothing special to see here :-)

What should I do in the second creation server? Should there be res.end () there

You should put some real, useful server logic. You have not described what your server is doing, and I do not think that this is relevant to the question you are doing. Whether res.end() should be there or not is a function of what the server does. So again there is nothing to see here :-)

+4
source

If you want to see a near real scene, try adding the hostname to funciton:

 }).listen(3002,'127.0.0.1'); 

and then try connecting from another computer (or with the same computer, but using an IP network). If your network IP address is 192.12.13.14, try:

 http://192.12.13.14:3002 

and

 http://192.12.13.14:3000 

to see the difference

+1
source

All Articles