简体   繁体   中英

Nodejs: http-proxy redirect to available server

I am using the http-proxy npm module for connecting multiple servers to a single port.

I wrote the following code and it's working fine:

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

My problem:

If one of my servers (for example port 3002) is not started or has an error, how can I automatically redirect requests to the other available server (ie port 3001)?

I've been using the http-proxy-rules extension as described here: https://github.com/donasaur/http-proxy-rules

I set up some rules and it gives the option to default if the page requested doesn't exist:

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

The default bit being relevant to you. There's also some code which states a message to display:

res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('The request url and path did not match any of the listed rules!');

I haven't tested this extensively but certainly got the redirection if a rule wasn't matched working - might be of some help to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM