[英]With or without the end event for request, what's the difference?
我是Node.js的新手。 我想知道这两段代码有什么区别:
var http = require("http");
http.createServer(function(request,response) {
request.addListener("end", function(){
console.log(request);
});
}).listen(8888);
和
var http = require("http");
http.createServer(function(request,response) {
console.log(request);
}).listen(8888);
换句话说,由于每次服务器完成接收数据时都会触发end
事件,所以为什么要使用它呢? 一个新手问题。
我不是NodeJS专家,但是从逻辑上来说,以下内容来自文档。
考虑一个上传大文件的请求。 当请求第一次到达服务器时,将调用传递给createServer
的回调。 当请求已完全发送后,将触发request
对象上的end
事件(继承自ReadableStream
)。 那将是完全不同的时代。
您的第二个代码可能无法满足您的期望,因为console.log(...)会在每次传入请求时运行。 但是无法判断请求是否已经完成(即已完全发送到服务器)。
每次关闭连接并完成请求时(即每次有人请求数据时),您的第一个代码都会运行console.log(...)。 然后,您可以使用传输的数据。 因此,您可能想使用(通常在处理请求时使用)是第一个代码。
如果要将任何数据发送到此服务器,则意味着必须使用该request.listener来获取该数据。
var http = require("http");
http.createServer(function(req,response) {
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
console.log('POSTed: ' + querystring.parse(body).urDataName);
var data=querystring.parse(body).urData;//here u can get the incoming data
});
}).listen(8888);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.