search

Home  >  Q&A  >  body text

关于node.js中response的end事件是否一定要先监听了data事件才能被emit

//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

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

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

伊谢尔伦伊谢尔伦2778 days ago593

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:52:21

    end is an event generated after reading the data.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 13:52:21

    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

    reply
    0
  • PHPz

    PHPz2017-04-17 13:52:21

    Owner,

    What should I do if I never enter the data?


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

    reply
    0
  • Cancelreply