Your first problem is related to changeOrigin
: that will send a Host
header to the remote server which includes a port number, and both sites you mention can't handle that.
Instead, try this:
req.headers.host = urlObj.host;
req.url = urlObj.path;
proxy.proxyRequest(req, res, {
host: urlObj.host,
port: 80,
enable : { xforward: true }
});
As for your other problem, I think it might be related to websites that don't serve their content as UTF-8 (which is the encoding that .toString()
will use if you don't pass it an encoding). Does it happen always, or just with some sites?
FWIW, harmon is a middleware for node-http-proxy
which provides a nice way of rewriting responses. It might be an overkill for your situation, but it might also solve your problem.
EDIT: here's a minimal example that seems to work just fine for both posterkoenig.ch
and www.verkehrsclub.ch
(homepages as well as subpages):
var httpProxy = require('http-proxy');
var url = require('url');
httpProxy.createServer(function(req, res, proxy) {
var urlObj = url.parse(req.url);
req.headers.host = urlObj.host;
req.url = urlObj.path;
proxy.proxyRequest(req, res, {
host : urlObj.host,
port : 80,
enable : { xforward: true }
});
}).listen(9000, function () {
console.log("Waiting for requests...");
});