我正在使用 http-proxy 用于将多个服务器连接到单个端口的 npm 模块。
我编写了以下代码并且运行良好:
var http = require('http');
var httpProxy = require('http-proxy');
// Proxy Address
var proxyAddresses = [
{
host: "localhost",
port: 3001
},
{
host: "localhost",
port: 3002
}
];
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '9090');
app.set('port', port);
//Create a set of proxy servers
var proxyServers = proxyAddresses.map(function (target) {
return new httpProxy.createProxyServer({
target: target
});
});
/**
* Create HTTP server.
*/
var server = http.createServer(function(req, res){
var proxy = proxyServers.shift();
proxy.web(req, res);
proxyServers.push(proxy);
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, function(){console.log("server is listening on port " + port);});
server.on('error', onError);
server.on('listening', onListening);
我的问题:
如果我的一个服务器(例如端口 3002)没有启动或有错误,我如何自动将请求重定向到另一个可用的服务器(即端口 3001)?
最佳答案
我一直在使用 http-proxy-rules 扩展,如下所述:https://github.com/donasaur/http-proxy-rules
我设置了一些规则,如果请求的页面不存在,它会提供默认选项:
var proxyRules = new HttpProxyRules({
rules: {
'.*/test': 'http://localhost:8080/cool', // Rule (1)
'.*/test2/': 'http://localhost:8080/cool2/', // Rule (2)
'/posts/([0-9]+)/comments/([0-9]+)': 'http://localhost:8080/p/$1/c/$2', // Rule (3)
'/author/([0-9]+)/posts/([0-9]+)/': 'http://localhost:8080/a/$1/p/$2/' // Rule (4)
},
default: 'http://localhost:8080' // default target
默认位与您相关。还有一些代码表示要显示的消息:
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('The request url and path did not match any of the listed rules!');
我没有对此进行过广泛测试,但如果规则不匹配,肯定会进行重定向 - 可能对您有所帮助。
关于node.js - Node : http-proxy redirect to available server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46973262/