node.js - Node : http-proxy redirect to available server

标签 node.js http-proxy node-http-proxy

我正在使用 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/

相关文章:

javascript - 如何上传 zip 文件并在 Express js 中为其内容提供永久链接

java - 通过另一个代理从一个代理连接到互联网

javascript - 对于一个端口上只有一个应用程序的 Node 应用程序,使用代理服务器(例如 node-http-proxy)有什么意义?

angularjs - 在执行 gulp build :dist 时设置代理或后端 URL

javascript - nestjs multer 获取 multer 存储后的新文件名列表

javascript - 函数声明和函数表达式可以互换使用吗?

python - 有人可以解释这条扭曲的事吗?

Kubernetes:在 K8s 中,在入口及其服务之间设置自定义代理的惯用方式是什么?

node.js - node-http-proxy 路由器表中的通配符

javascript - Node : Would App Run Faster if Freeze Objects?