来自http请求的Node.js响应在不包含'data'事件的情况下不调用'end'事件

所以我有一个简单的客户端应用程序与node.js中的服务器端应用程序进行通信。 在客户端,我有以下代码:

function send (name) { http.request({ host: '127.0.0.1', port: 3000, url: '/', method: 'POST' }, function (response) { response.setEncoding('utf8'); response.on('data', function (data) { console.log('did get data: ' + data); }); response.on('end', function () { console.log('\n \033[90m request complete!\033[39m'); process.stdout.write('\n your name: '); }); response.on('error', function (error) { console.log('\n Error received: ' + error); }); }).end(query.stringify({ name: name})); //This posts the data to the request } 

奇怪的是,如果我不包括“数据”事件通过:

  response.on('data', function (data) { console.log('did get data: ' + data); }); 

响应的“结束”事件永远不会被触发。

服务器代码如下所示:

 var query = require('querystring'); require('http').createServer(function (request, response) { var body = ''; request.on('data', function (data) { body += data; }); request.on('end', function () { response.writeHead(200); response.end('Done'); console.log('\n got name \033[90m' + query.parse(body).name + '\033[39m\n'); }); }).listen(3000); 

我想知道为什么这是发生在文档(据我所知)不需要您监听数据事件以closures响应会话。

只有当所有的数据被消耗,才会调用'end' ,查看下面的参考:

事件:'结束'

这个事件在没有更多数据提供的时候触发。

请注意,除非数据完全消耗,否则结束事件不会触发。 这可以通过切换到stream动模式,或通过重复调用read()直到完成。

但是为什么你需要调用.on('data',..) ? 答案是

如果你附加一个数据事件监听器,那么它将把stream切换到stream模式,数据将尽快传递给你的处理程序。

所以基本上通过添加data监听器,它将stream转换为stream模式并开始使用数据。

请检查这个链接更多的参考。