3

关于节点http.request(options, callback)方法的一个小问题。
我从文档中获得了以下示例代码:

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

问题: 什么时候触发实际的 HTTP 请求?

是在将请求分配给req变量时(第 8 行),还是在req.end()

4

1 回答 1

4

示例后面的文档中的解释是正确的:

请注意,在示例req.end()中被调用。必须始终调用req.end http.request()() 以表示您已完成请求 - 即使没有数据写入请求正文。

的调用req.end()是强制性的。请注意,这req是一个http.ClientRequest. 的文档http.ClientRequest.prototype.end为您提供了最后的线索:

request.end([data], [encoding])
完成发送请求

于 2012-12-22T20:36:52.580 回答