【发布时间】:2015-06-24 04:41:53
【问题描述】:
我正在创建新服务器来监听新端口(下面是第二个创建),现在当我使用某个端口调用应用程序时,我想将其重定向到新创建的服务器端口,并将消息放入浏览器中“请求路由到 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(这 正是我需要的我可以在浏览器中看到)但我得到了 错误 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,为什么要将端口 9009 代理到端口 3000?当您代理时,您使内容在端口 9009 上可用,在端口 3000 上也可用。如果您只是想将流量从端口 3000 发送到另一个端口,请不要使用代理,只需 http 重定向它们。
-
您希望每个访问者都被重定向到一个新的唯一端口,还是所有访问者都被重定向到端口 9009?
-
@dandavis-让现在假设应用程序将路由到 9009 是否可能?你能帮忙怎么做吗?
标签: javascript node.js url-redirection http-proxy node-http-proxy