2017-10-27 8 views
3

私はhttp-proxy npmモジュールを使用して、複数のサーバを1つのポートに接続します。 Nodejs:http-proxyが利用可能なサーバにリダイレクト

は、私は次のコードを書き、それが正常に働いています:

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プロキシ・ルール拡張を使用してきた

答えて

0

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!'); 

私は広範囲にこれをテストしたが、確かにルールが作業を一致しなかった場合は、リダイレクトを持っていない - あなたにいくつかの助けになるかもしれません。

関連する問題