Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proxy request to new port with http-proxy

I use this code I want to create proxy that all the application calls to port 3000 will be routed "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 run the application with original port(3000) I see in the browser

request successfully proxied to 3002

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

  • What should I put in production inside the second create server ? I mean instead of the

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

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

like image 366
John Jerrby Avatar asked Aug 10 '15 06:08

John Jerrby


People also ask

What port does HTTP proxy use?

3128 is the default port number where the HTTP/TCP proxy listens for HTTP traffic. Any client applications that communicate with the proxy must also be set to the same port.

What is HTTP proxy request?

What Does HTTP Proxy Mean? An HTTP Proxy serves two intermediary roles as an HTTP Client and an HTTP Server for security, management, and caching functionality. The HTTP Proxy routes HTTP Client requests from a Web browser to the Internet, while supporting the caching of Internet data.


1 Answers

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

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

What should I put in production inside the second create server ?
Does the res.end() should also be there

You should put some real, useful server logic. You didn't describe what your server does, and I don't think it's relevant to the question that you do. Whether res.end() should be there or not is a function of what the server does. So again, nothing to see here :-)

like image 78
Amit Avatar answered Oct 15 '22 08:10

Amit