简体   繁体   中英

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

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

If you want to see a close real scenary try adding a hostname in the listen funciton:

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

and then try to connect from other computer (or with the same computer but using your network IP). If your net IP is 192.12.13.14 try:

http://192.12.13.14:3002 

and

http://192.12.13.14:3000

to see the diference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM