关于node.js中response的end事件是否一定要先监听了data事件才能被emit
伊谢尔伦
伊谢尔伦 2017-04-17 13:50:21
0
3
591
//server.js
var qs = require('querystring');
require('http').createServer(function(req, res){
    var body = '';
    req.on('data', function(chunk){
        body += chunk;
    });
    req.on('end', function(){
        res.writeHead(200);
        res.end('Done');
        console.log('\n  got name \033[90m' + qs.parse(body).name + '\033[39m\n');
    });
}).listen(3000);

//client.js
var http = require('http'), qs = require('querystring');
function send(theName){
    http.request({
        host: '127.0.0.1',
        port: 3000,
        url: '/',
        method: 'POST'
    }, function(res){
        res.setEncoding('utf8');
        //res.on('data', function(){return ;});
        res.on('end', function(){
            console.log('\n  \033[90m request complete!\033[39m');
            process.stdout.write('\n  your name: ');
        });
    }).end(qs.stringify({name: theName}));
}
process.stdout.write('\n  your name: ');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', function(name){
    send(name.replace('\n', ''));
});

-----------------------------------------------------------------------------------------------摘自《了不起的Node.js》P98 - P99

  • 将client.js中监听data的事件注视掉的话 就不会执行end事件中的回调函数

  1. 希望能够帮忙解释一下, 谢谢.

  2. 顺便问一下 遇到这种问题应该如何解决 好让我下次能够自己解决, 谢谢.

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(3)
Ty80

end is an event generated after reading the data.

小葫芦

I also encountered the same problem as the person in question today. After I found your problem, I suddenly understood it. Because the server-side end event is triggered after the server-side reads the request data, the server-side sends head and Done to the client. Therefore, in the client's stream, there is still data from the server that has not been received, so the end event will not be triggered~
You can do this in the end event

res.on('data', function(chunk){console.log(chunk)});

This way you will see Done. Then the end event will be triggered

PHPzhong

Owner,

What should I do if I never enter the data?


Submit the form through $.post, but the data cannot be obtained...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template