In the example, there has a lot of proxy.web(req, res, { target: 'http://host:port' });
If the req.url is "http://github.com/nodejitsu/node-http-proxy", the target must be "http://github.com/"?
Why target can not be empty, and "http-proxy" extract the target from req.url?
By the way, the code blow could extract target from req.url:
url = require('url')
target = url.parse(req.url)
result = proxy.web(req, res, {
target: target.protocol + '//' + target.host
})
I think you are misunderstanding the purpose of this module. This module is meant to take a request and FORWARD it to another server. You must specify the URL to forward it to. In your example above, you would be forwarding the request to your own server, creating an infinite loop (not to mention that you cannot get the protocol or the target from req.url).
below works for me.
var httpProxy = require('http-proxy')
var proxy = httpProxy.createProxy();
var options = {
'foo.com': 'http://foo.com:8001',
'bar.com': 'http://bar.com:8002'
}
require('http').createServer(function(req, res) {
proxy.web(req, res, {
target: options[req.headers.host]
});
}).listen(80);
Most helpful comment
below works for me.
var httpProxy = require('http-proxy')
var proxy = httpProxy.createProxy();
var options = {
'foo.com': 'http://foo.com:8001',
'bar.com': 'http://bar.com:8002'
}
require('http').createServer(function(req, res) {
proxy.web(req, res, {
target: options[req.headers.host]
});
}).listen(80);