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

More elegant way of creating reverse proxy with Node.js

本文关键字:方式 代理 Node js 创建 使用      更新时间:2023-09-26

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

这是代理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地址进行硬编码的情况下实现相同的目标?

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

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