2017-10-27 9 views
3

하나의 포트에 여러 서버를 연결하기 위해 http-proxy npm 모듈을 사용하고 있습니다. 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)로 자동으로 리디렉션합니까? https://github.com/donasaur/http-proxy-rules

내가 몇 가지 규칙을 설정하고 요청 된 페이지가 존재하지 않는 경우는 기본적으로 할 수있는 옵션을 제공합니다 : 여기에 설명 된대로

답변

0

I는 HTTP 프록시-규칙 확장을 사용하고

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

나는이 광범위하게 테스트하지만, 규칙이 작업과 일치하지 않은 경우 확실히 리디렉션을 없어는 - 당신에게 어떤 도움이 될 수 있습니다.

관련 문제