关于节点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()
?
答案 0 :(得分:4)
说明正好在示例后面的文档中:
请注意,在示例中调用了
req.end()
。使用http.request()
时,必须始终调用req.end()来表示您已完成请求 - 即使没有数据写入请求正文。
req.end()
的来电是强制性的。请注意,req
是http.ClientRequest
。 http.ClientRequest.prototype.end
的文档为您提供了最终线索:
request.end([data], [encoding])
完成发送请求