使用Node.js创建反向代理的更优雅方式

时间:2015-01-20 11:56:13

标签: javascript node.js reverse-proxy node-http-proxy hapijs

我正在使用hapi.js在应用程序中提供html内容。现在我需要代理一些可能使用websockets的服务。

以下是http://localhost:4000中代理http://localhost:5000/my/app的工作代码:

hapi = require "hapi" 
http-proxy = require 'http-proxy'
server = hapi.create-server 5000 

server.route do
  method: '*'
  path: '/my/app/{f*}'
  handler: 
    proxy:
      map-uri: (request, callback) -> 
        resourceUri = request.url.path.replace('/my/app/', '/')
        url = 'http://localhost:4000' + resourceUri
        console.log 'url: ', url
        callback(null,url);
      pass-through: true
      xforward: true

ws-proxy = http-proxy.create-proxy-server do
  target:'http://localhost:4000/socket.io/'

ws-proxy.on 'error', (err, req, res) !-> 
  console.log "error caught: ", err#, req

server.start !->
  server.listener.on 'upgrade', (req, socket, head) !->
    console.log "upgrade dedected"
    ws-proxy.ws(req, socket, head)
    #console.log req, socket, head
  console.log 'Proxy started @ ' + server.info.uri

自动生成的Javascript代码为:

// Generated by LiveScript 1.3.1
(function(){
  var hapi, httpProxy, server, wsProxy;
  hapi = require("hapi");
  httpProxy = require('http-proxy');
  server = hapi.createServer(5000);
  server.route({
    method: '*',
    path: '/my/app/{f*}',
    handler: {
      proxy: {
        mapUri: function(request, callback){
          var resourceUri, url;
          resourceUri = request.url.path.replace('/my/app/', '/');
          url = 'http://localhost:4000' + resourceUri;
          console.log('url: ', url);
          return callback(null, url);
        },
        passThrough: true,
        xforward: true
      }
    }
  });
  wsProxy = httpProxy.createProxyServer({
    target: 'http://localhost:4000/socket.io/'
  });
  wsProxy.on('error', function(err, req, res){
    console.log("error caught: ", err);
  });
  server.start(function(){
    server.listener.on('upgrade', function(req, socket, head){
      console.log("upgrade dedected");
      wsProxy.ws(req, socket, head);
    });
    console.log('Proxy started @ ' + server.info.uri);
  });
}).call(this);

如果没有对http://localhost:4000/socket.io/的websocket地址进行硬编码,有没有办法实现相同的目标?

1 个答案:

答案 0 :(得分:0)

因此,通过阅读代码,您始终代理http://localhost:4000/socket.io/,但是您希望这是动态的吗?

您可以将您希望代理的服务器作为参数传递给初始请求吗?您可以在WebSocket构造函数的protocol字段中传递此信息。然后在服务器on-open事件上阅读此内容。