NodeJS + http-proxy - 对象没有方法“恢复”;

发布于 2024-12-25 22:27:15 字数 4387 浏览 0 评论 0原文

这个问题的奇怪之处在于,在我离开办公桌之前,我有一个工作示例(尽管握手后没有传输数据),现在我似乎无法正常工作,尽管恢复了一些小问题我所做的改变。

我使用 NodeJS + http-proxy 模块将 .html 文件的请求代理到 Apache,所有其他请求都由 NodeJS 处理。

这是我的 server.js 代码:

CometServer = (function() {

  var instance;

  function __construct() {

    var apachePort = 3000;
    var nodeJsPort = 3001;
    var apacheHost = 'localhost';
    var nodeJsHost = 'localhost';
    var httpProxy = require('/root/node_modules/http-proxy');
    var io = require('/root/node_modules/socket.io');
    var fs = require('/root/node/lib/fs');
    var path = require('/root/node/lib/path');
    var url = require('/root/node/lib/url');
    var apacheUrls = [
      /.*\.html/,
      /^\/$/
    ];

    function proxyRequests(request, response, proxy) {

      // Check if the URL is a comet request or not.
      var shouldProxy = apacheUrls.some(function(requestUrl) {
        return requestUrl.test(request.url);
      });

      // If 'request.url' matches any of the 'apacheUrls' then proxy to Apache.
      if (shouldProxy) {

        return proxy.proxyRequest(request, response, {
          host: apacheHost,
          port: apachePort
        });

      }

      // Not proxied to Apache; this is a comet request and should be processed by NodeJS.
      return handleUnproxiedRequests(request, response);

    }

    function handleUnproxiedRequests(request, response) {
      var uri = url.parse(request.url).pathname;
      var filePath = path.join(process.cwd(), '..', uri);

      var extname = path.extname(filePath);
      var contentType = 'text/javascript';

      path.exists(filePath, function(exists) {
        if (exists) {
          var fileStream = fs.createReadStream(filePath);
          fileStream.on('data', function (data) {
            response.writeHead(200, {
              'Content-Type': contentType
            });
            response.write(data);
            response.end();
          });
        }
        else {
          response.writeHead(404);
          response.end();
        }
      });
      return;
    }

    function bootstrap() {

      // Create a http proxy server and use the 'proxy' conditionally inside the request handler.
      var server = httpProxy.createServer(nodeJsPort, nodeJsHost, {
        target: {
          host: nodeJsHost,
          port: nodeJsPort
        }
      }, proxyRequests);

      // Get the http proxy server to listen to a port.
      server.listen(nodeJsPort);

      // Get socket.io to listen to the proxy server.
      var listener = io.listen(server);

      var something = listener.on('connection', function(socket) {
        console.log('socket connected');
        socket.on('handshake', function(pid) {
          console.log('socket? ' + pid);
        })
      });

    }

    // Bootstrap server.
    bootstrap();

    return { }

  }

  return {
    getInstance: function() {
      // Instantiate only if the instance doesn't already exist.
      if (!instance) {
        instance = __construct();
      }
      return instance;
    }
  }
})();

// Initialize the comet server.
CometServer.getInstance();

和客户端 js:

var socket = io.connect();
console.log('Connected');
socket.on('connect', function(data) {
  console.log('Sending handshake');
  socket.emit('handshake', 1);
});

请注意,此代码目前有点混乱,因为它还处于生产的早期阶段。然而,如果你愿意,如果你认为我可以/应该以不同的方式做一些事情,请随意批评它。

这是我尝试访问 .html 页面时收到的错误消息:

/root/node_modules/http-proxy/lib/node-http-proxy/http-proxy.js:334
      ? buffer.resume()
           ^
TypeError: Object #<Object> has no method 'resume'
    at [object Function].proxyRequest (/root/node_modules/http-proxy/lib/node-http-proxy/http-proxy.js:334:16)
    at proxyRequests (/var/www/html/Comet/server.js:139:22)
    at Server.<anonymous> (/root/node_modules/http-proxy/lib/node-http-proxy.js:321:7)
    at Manager.handleRequest (/root/node_modules/socket.io/lib/manager.js:531:28)
    at Server.<anonymous> (/root/node_modules/socket.io/lib/manager.js:112:10)
    at Server.emit (events.js:70:17)
    at HTTPParser.onIncoming (http.js:1479:12)
    at HTTPParser.onHeadersComplete (http.js:102:31)
    at Socket.ondata (http.js:1375:22)
    at TCP.onread (net.js:334:27)

从我读到的内容来看,数据似乎是缓冲的而不是流式传输的,但我真的不知道如何解决这个问题,因为我'我对 API 非常陌生(这是我的第一个 NodeJS 项目)。

任何帮助将不胜感激,因为我已经用头撞砖墙很长一段时间了。

The strange thing about this problem is that I had a working example (albeit with no data being transferred post-handshake) before I went away from my desk, and now I can't seem to get this working properly, despite reverting the few minor changes I made.

I'm using NodeJS + the http-proxy module to proxy requests for .html files to Apache, and all other requests are being processed by NodeJS.

Here's my server.js code:

CometServer = (function() {

  var instance;

  function __construct() {

    var apachePort = 3000;
    var nodeJsPort = 3001;
    var apacheHost = 'localhost';
    var nodeJsHost = 'localhost';
    var httpProxy = require('/root/node_modules/http-proxy');
    var io = require('/root/node_modules/socket.io');
    var fs = require('/root/node/lib/fs');
    var path = require('/root/node/lib/path');
    var url = require('/root/node/lib/url');
    var apacheUrls = [
      /.*\.html/,
      /^\/$/
    ];

    function proxyRequests(request, response, proxy) {

      // Check if the URL is a comet request or not.
      var shouldProxy = apacheUrls.some(function(requestUrl) {
        return requestUrl.test(request.url);
      });

      // If 'request.url' matches any of the 'apacheUrls' then proxy to Apache.
      if (shouldProxy) {

        return proxy.proxyRequest(request, response, {
          host: apacheHost,
          port: apachePort
        });

      }

      // Not proxied to Apache; this is a comet request and should be processed by NodeJS.
      return handleUnproxiedRequests(request, response);

    }

    function handleUnproxiedRequests(request, response) {
      var uri = url.parse(request.url).pathname;
      var filePath = path.join(process.cwd(), '..', uri);

      var extname = path.extname(filePath);
      var contentType = 'text/javascript';

      path.exists(filePath, function(exists) {
        if (exists) {
          var fileStream = fs.createReadStream(filePath);
          fileStream.on('data', function (data) {
            response.writeHead(200, {
              'Content-Type': contentType
            });
            response.write(data);
            response.end();
          });
        }
        else {
          response.writeHead(404);
          response.end();
        }
      });
      return;
    }

    function bootstrap() {

      // Create a http proxy server and use the 'proxy' conditionally inside the request handler.
      var server = httpProxy.createServer(nodeJsPort, nodeJsHost, {
        target: {
          host: nodeJsHost,
          port: nodeJsPort
        }
      }, proxyRequests);

      // Get the http proxy server to listen to a port.
      server.listen(nodeJsPort);

      // Get socket.io to listen to the proxy server.
      var listener = io.listen(server);

      var something = listener.on('connection', function(socket) {
        console.log('socket connected');
        socket.on('handshake', function(pid) {
          console.log('socket? ' + pid);
        })
      });

    }

    // Bootstrap server.
    bootstrap();

    return { }

  }

  return {
    getInstance: function() {
      // Instantiate only if the instance doesn't already exist.
      if (!instance) {
        instance = __construct();
      }
      return instance;
    }
  }
})();

// Initialize the comet server.
CometServer.getInstance();

And the client side js:

var socket = io.connect();
console.log('Connected');
socket.on('connect', function(data) {
  console.log('Sending handshake');
  socket.emit('handshake', 1);
});

Please note that this code is a little messy at the moment as it's in very early stages of production. However, feel free to critique it if you like, if you think there's something I could/should be doing in a different way.

Here's the error message I receive when I try to access a .html page:

/root/node_modules/http-proxy/lib/node-http-proxy/http-proxy.js:334
      ? buffer.resume()
           ^
TypeError: Object #<Object> has no method 'resume'
    at [object Function].proxyRequest (/root/node_modules/http-proxy/lib/node-http-proxy/http-proxy.js:334:16)
    at proxyRequests (/var/www/html/Comet/server.js:139:22)
    at Server.<anonymous> (/root/node_modules/http-proxy/lib/node-http-proxy.js:321:7)
    at Manager.handleRequest (/root/node_modules/socket.io/lib/manager.js:531:28)
    at Server.<anonymous> (/root/node_modules/socket.io/lib/manager.js:112:10)
    at Server.emit (events.js:70:17)
    at HTTPParser.onIncoming (http.js:1479:12)
    at HTTPParser.onHeadersComplete (http.js:102:31)
    at Socket.ondata (http.js:1375:22)
    at TCP.onread (net.js:334:27)

From what I've read, it looks like the data is buffered rather than streamed, but I don't really have any idea how to fix this as I'm very new to the API (this is my first NodeJS project).

Any help would be appreciated, as I've been banging my head against a brick wall with this for quite a while now.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╄→承喏 2025-01-01 22:27:15

嗯,似乎传递到 createServer 方法的一些参数是无关的 - 我通过以下方法修复了该问题:

var server = httpProxy.createServer(proxyRequests);

我不完全确定为什么会这样,以及为什么我之前的示例在最初正确运行后停止工作。

Hmm, it seems that some of the arguments passed into the createServer method were extraneous - I fixed the issue with the following:

var server = httpProxy.createServer(proxyRequests);

I'm not entirely sure why this worked, and why my previous example stopped working after originally running correctly.

霞映澄塘 2025-01-01 22:27:15

我认为您正在遇到这个问题:
https://github.com/joyent/node/issues/1956

I think you are experiencing this issue:
https://github.com/joyent/node/issues/1956

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文