【问题标题】:calling nodejs request.end() method before setting up the listeners在设置监听器之前调用 nodejs request.end() 方法
【发布时间】:2014-09-20 04:03:07
【问题描述】:

在 nodejs 文档http://nodejs.org/api/http.html#http_event_connect_1 中,示例代码在设置侦听器之前调用 request.end()(即 req.on(...) 方法)。示例代码片段如下所示。

  var req = http.request(options);
  req.end();

  req.on('connect', function(res, socket, head) {
    console.log('got connected!');

    // make a request over an HTTP tunnel
    socket.write('GET / HTTP/1.1\r\n' +
                 'Host: www.google.com:80\r\n' +
                 'Connection: close\r\n' +
                 '\r\n');
    socket.on('data', function(chunk) {
      console.log(chunk.toString());
    });
    socket.on('end', function() {
      proxy.close();
    });
  });

如果这种情况下,请求没有在设置监听器之前立即结束,那么监听器可能永远不会被调用。

【问题讨论】:

    标签: node.js


    【解决方案1】:

    req.end() 调用表示您已完成将请求正文发送到服务器(在这种情况下没有请求正文),而不是完整的请求/响应周期已完成。此外,http.request 将延迟与服务器的连接开始,直到下一次通过运行循环,让您有机会设置您的侦听器。

    所以,本质上,它正在做这样的事情:

    1. 创建新请求
    2. 告诉请求我们已完成发送我们要发送的数据
    3. 告诉请求让我们知道我们何时连接到服务器

    下一个 Run Loop Pass

    1. 尝试连接到服务器

    连接成功后

    1. 发送请求等

    【讨论】:

      猜你喜欢
      • 2012-07-06
      • 2016-01-01
      • 2014-06-02
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 2018-07-27
      • 2020-12-21
      相关资源
      最近更新 更多