during my studies i have to create a nodejs webserver environment including 2 nodejs webserver and 1 nodejs loadbalancer via http-proxy (module). Therefore i built 2 instances of node js listening to port 8081 and 8082. Example Server A (localhost:8081)
var args = process.argv.splice(2);
var http = require('http');
function whoareU() {
var n = 'A';
return n;
}
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type' : 'text/plain'});
res.end('Server: ' + whoareU());
});
server.listen(args[0] || 8081);
... ServerB is similar, just changed Port 8082 and Identifier B.
On the second hand i built a "loadbalace" instance via http-proxy listening to port 8080
var http = require('http'),
httpProxy = require('http-proxy');
var servers = [{host :'127.0.0.1', port :8081}, {host : '127.0.0.1',port :8082}];
httpProxy.createServer(function (req, res, proxy) {
var target = servers.shift();
proxy.proxyRequest(req, res, target);
servers.push(target);
}).listen(8000);
MY INTENTION: If i open the URL 127.0.0.1:8080 i wanna see changing Outputs. "Server: A" or "Server: B". BUT IT DOESNT WORK!!!!!!!!! The message:
Error: Must provide a proper URL as target
at ProxyServer.<anonymous> (D:\nodejsmain\node_modules\http-proxy\lib\http-p
roxy\index.js:68:35)
at Server.closure (D:\nodejsmain\node_modules\http-proxy\lib\http-proxy\inde
x.js:125:43)
at Server.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2112:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23
)
at Socket.socket.ondata (http.js:1970:22)
at TCP.onread (net.js:527:27)
Question A: Why? ;-) By the way: the output of 127.0.0.1:8081 or 127.0.0.1:8082 works fine!
In addition to that one further question (Question B) to my code: How can i understand args[0] in all config-files (server.listen(args[0] || 8081);) ... Before i did more easy configurations like the following sniped shows and i didnt need it.
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200,
{'content-type': 'text/plain; charset=utf-8'});
response.write('Huhu ');
response.end('Stefan\n');
}).listen(8080, '127.0.0.1');
So thank u for helping me in both questions (A+B).