尝试将应用程序重定向到新服务器端口时出错

Error while trying to re-direct application to new server port

我正在创建新服务器来监听新端口(下面是第二个创建),现在当我用某个端口调用应用程序时,我想将它重定向到新创建的服务器端口,并将消息放在浏览器 "Request route to on 9009"

我使用下面的代码创建服务器

httpProxy = require('http-proxy');

proxy = httpProxy.createProxyServer({});

    http.createServer(function (req, res) {
            var hostname = req.headers.host.split(":")[0];
             if  (hostname ==='localhost') {
              proxy.web(req, res, {target: 'http://localhost:9009'});
             }     
}    }).listen(3000, function () {
        console.log('App listening on port 3000');
    });
now I create the new server

http.createServer(function (req, res) {
 res.writeHead(302, {
    'Location': 'http://localhost:9009'
 });

   res.end("Request route to  9009");
}).listen(9009);

现在,当我输入 localhost:3000 时,它 将我 重定向到 localhost:9009(这正是我需要的 我可以在浏览器中看到)但是我得到了 error This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS

如果我从 second createServer 函数中删除以下

res.writeHead(302, {
    'Location': 'http://localhost:9009'
 }); 

它不是重定向,我没有收到错误... 我是不是把这段代码放在了错误的地方?或者有什么不同的方法吗? 我用 https://github.com/nodejitsu/node-http-proxy

更新

我改代码如下

var http = require('http');

http.createServer(function (req, res) {
    console.log("Server created");
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write('9009 here' + '\n' + JSON.stringify(req.headers, true, 2));
    res.end();
}).listen(9009);

http.createServer(function(req, res) {
    console.log("Server 2 created");
    res.writeHead(302, {
        'Location': 'http://localhost:9009/'
    });
    res.end("Request route to 9009");
}).listen( 3001 );

在您显示的代码中,代理使端口 9009 显示在端口 3000 上,更像是 apache url 重写而不是 url 重定向。

如果你想把登陆3000端口的访问者发送到9009端口,简单的http就够了:

var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('9009 here' + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen( 9009 );

http.createServer(function(req, res) {
    res.writeHead(302, {
        'Location': 'http://X.X.X.X:9009/' // fix me
     });
    res.end("Request route to  9009");
}).listen( 3000 );

如果您希望每个访问者都访问一个新的个人端口,这是一种简单但幼稚的方法(不考虑重复端口,这会使节点崩溃 1/1000 次):

var http = require('http');
http.createServer(function(req, res) {
    var port=Math.floor(Math.random()*1000)+12000;
    http.createServer(function (req, res) {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.write( port + ' talking' + '\n' + JSON.stringify(req.headers, true, 2));
      res.end();
    }).listen( port );

    res.writeHead(302, {
        'Location': 'http://X.X.X.X:'+ port +'/'  // fix me
     });
    res.end("Request route to " + port );
}).listen( 3000 );