vhosts与http-proxy和express

时间:2014-01-19 22:44:01

标签: node.js http-proxy node-http-proxy

我正在尝试使用http-proxy

模拟nodeje express上的虚拟主机

httpProxy.createServer({
    hostnameOnly : true,
    router : {
        'secure.domain.com' : '127.0.0.1:9000'
    }
}).listen(8080);

(function(){
    var app = express();
    app.set('port', 9000);

    // Web request
    app.get('/*', function(request, response){
        response.end('wolla');
    });

    var server = http.createServer(app).listen(app.get('port'), function(){
      console.log('Express server listening on port '+app.get('port'));
    });
})();

简单的例子用于获取灵感,但返回相同的错误

var http = require('http'),
    httpProxy = require('http-proxy');
//
// Create a basic proxy server in one line of code...
//
// This listens on port 8000 for incoming HTTP requests 
// and proxies them to port 9000
httpProxy.createServer(9000, 'localhost').listen(8000);

//
// ...and a simple http server to show us our request back.
//
http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9000);

错误

/var/www/node/node_modules/http-proxy/lib/http-proxy/passes/web-incoming.js:103
    var proxyReq = (options.target.protocol === 'https:' ? https : http).reque
                                  ^
TypeError: Cannot read property 'protocol' of undefined
    at Array.stream [as 3] (/var/www/node/node_modules/http-proxy/lib/http-proxy/passes/web-incoming.js:103:35)
    at ProxyServer.<anonymous> (/var/www/node/node_modules/http-proxy/lib/http-proxy/index.js:83:21)
    at Server.closure (/var/www/node/node_modules/http-proxy/lib/http-proxy/index.js:116:43)
    at Server.EventEmitter.emit (events.js:98:17)
    at HTTPParser.parser.onIncoming (http.js:2108:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:121:23)
    at Socket.socket.ondata (http.js:1966:22)
    at TCP.onread (net.js:525:27)
Worker 31599 died (8). Restarting...
Express server listening on port 9000

1 个答案:

答案 0 :(得分:0)

如果您仔细观察docs,这就是您需要做的工作:

httpProxy.createServer({
  target: 'http://localhost:9000'
}).listen(8000);