请求何时被解雇? http.request()

时间:2012-12-22 20:32:47

标签: node.js

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

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()

1 个答案:

答案 0 :(得分:4)

说明正好在示例后面的文档中:

  

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

req.end()的来电是强制性的。请注意,reqhttp.ClientRequesthttp.ClientRequest.prototype.end的文档为您提供了最终线索:

  

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