我的代码中的 request.end 侦听器有什么问题

What is wrong with the listener for request.end in my code

本文关键字:侦听器 什么 问题 end request 代码 我的      更新时间:2023-09-26

我刚刚开始研究Node.js。我在 http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/中浏览了一个教程,我正在尝试执行他作为示例给出的脚本,但除非我在"end"事件上注释掉侦听器,否则它不起作用。

var http = require("http");
http.createServer(function (request, response) {
 // request.on("end", function () {
      response.writeHead(200, {
         'Content-Type': 'text/plain'
      });
      response.end('Hello HTTP!');
  // });
  //request.end();
}).listen(8080);

如果我在请求的"end"上注释侦听器,上面的代码工作正常,但是如果我取消注释它,那么它将无法正常工作。有人可以在这里帮助我吗?

谢谢哈尔沙。

事件侦听器上的请求实际上正在执行end是侦听结束事件并在执行该事件后触发回调函数。

您正在尝试触发end事件,甚至在该事件被执行之前。将请求end函数移到响应正文之外,这应该可以工作:

var http = require("http");
http.createServer(function (request, response) {    
    response.writeHead(200, {
        'Content-Type': 'text/plain'
    });    
    request.on("end", function () {      
        console.log("GOOD BYE!");       
    });
    response.end('Hello HTTP!'); 
}).listen(8080);

end 事件由 response.end() 调用后发出,如下所示:

var http = require('http');
http.createServer(function (request, response) {
    request.on('end', function () {
        console.log('end event called');
    });
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello HTTP!');
}).listen(8080);