2

我是 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每次服务器完成接收数据都会触发事件,为什么还要使用它呢?一个新手问题。

4

3 回答 3

2

我不是 NodeJS 专家,但以下内容合乎逻辑地来自文档。

考虑一个上传大文件的请求。你传入的回调createServer在请求第一次到达服务器时被调用;对象上的end事件request(继承自ReadableStream)在请求完全发送时触发。那将是完全不同的时代。

于 2013-08-23T09:10:10.453 回答
2

您的第二个代码可能不会按照您的预期执行,因为每次有传入请求时都会运行 console.log(...)。但是没有办法知道请求是否已经完成(即完全发送到服务器)。
您的第一个代码在每次连接关闭且请求完成时(即每次有人请求数据时)运行 console.log(...)。然后,您可以使用传输的数据。因此,您可能想要使用(并且通常在处理请求时使用)是第一个代码。

于 2013-08-23T12:58:05.467 回答
1

如果您要向该服务器发送任何数据,则意味着您必须使用该 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);
于 2013-08-23T09:21:53.597 回答