Http请求正在返回比预期的更多的数据

由于我不能评论这个问题的答案, 所以我想在这里提供一些帮助。

我有完全相同的代码,但输出如下所示:

/** * Created by Ramiro on 09/06/2015. */ // Load the http module to create an http server. var http = require('http'); // Configure our HTTP server to respond with Hello World to all requests. var server = http.createServer(function (request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); //console.log(dbHandler.GetDatabase()); var req = http.request('http://127.0.0.1:5984/_myUri', function(res) { res.setEncoding('utf8'); var body = ''; // Streams2 API res.on('readable', function () { var chunk = this.read() || ''; body += chunk; console.log('chunk: ' + Buffer.byteLength(chunk) + ' bytes'); }); res.on('end', function () { console.log('body: ' + Buffer.byteLength(body) + ' bytes'); }); req.on('error', function(e) { console.log("error" + e.message); }); }); req.end(); response.end(); }); // Listen on port 8000, IP defaults to 127.0.0.1 server.listen(3000); 

有了这个输出:

 chunk: 230 bytes chunk: 0 bytes body: 230 bytes chunk: 230 bytes chunk: 0 bytes body: 230 bytes chunk: 230 bytes chunk: 0 bytes body: 230 bytes 

这导致我推断:

  • res.on'可读'被调用两次:
  • 整个callback被称为三次。 需要你的build议。

这个“可读”的事件是针对每一个通过的块而引发的,有时会包含一个零散的。我相信这是发生在你的情况之中的,因为你的console.log行正在获得聚集的“body”值,而不是个人“块”,你看到两次。 (它返回230然后是0,但每次总数是230)。 为了获得全部数据,只需要连接在“结束”callback中调用的所有块。 看看这到哪里:

 var req = http.request('http://127.0.0.1:5984/_myUri', function(res) { res.setEncoding('utf8'); var body = ''; // Streams2 API res.on('readable', function () { var chunk = this.read() || ''; body += chunk; console.log('chunk: ' + Buffer.byteLength(chunk) + ' bytes'); }); res.on('end', function () { console.log('body: ' + Buffer.byteLength(body) + ' bytes'); }); req.on('error', function(e) { console.log("error" + e.message); }); }); req.end(); 

但这并不能解释3个电话。 (当我在我的代码中运行你的确切代码时,由于我上面解释的原因,我得到了多个“块”行,但是我只能得到一个总体集合,而且只有一个“主体”行)是更大testing程序的一部分吗? 如果是这样,也许在其他循环中被称为3次? 或者它可能会导致页面刷新或redirect几次,并发送不是“结束”信号的页眉。 我只是不太了解NodeJS中的这个函数是如何处理这种exception的。