我刚刚开始研究 Node.js。我在 http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/ 中发现了一个教程,我正在尝试执行他作为示例给出的脚本,但除非我注释掉“结束”事件的监听器,否则它无法正常工作。
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
函数移到响应正文之外,这样应该可以工作:
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);
关于javascript - 我的代码中 request.end 的监听器有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19559875/