繁体   English   中英

来自http请求的Node.js响应未调用'end'事件而不包括'data'事件

[英]Node.js response from http request not calling 'end' event without including 'data' event

所以我有一个简单的客户端应用程序与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);
    });

响应的'end'事件永远不会被触发。

服务器代码如下:

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

我想知道为什么当文档(据我所知)不需要你监听数据事件以关闭响应会话时发生这种情况。

只有在消耗了所有数据时才会调用'end' ,请查看下面的参考:

事件:'结束'

如果不再提供数据,则会触发此事件。

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

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

如果附加数据事件侦听器,则它会将流切换为流动模式,并且数据一旦可用就会传递给处理程序。

所以基本上通过添加data监听器,它将流更改为流动模式并开始使用数据。

请查看此链接以获取更多相关信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM