gpt4 book ai didi

javascript - Http 请求在主体中返回比预期更多的数据

转载 作者:可可西里 更新时间:2023-11-01 16:42:02 26 4
gpt4 key购买 nike

因为我无法评论 this question 的答案我想在这里得到一些帮助。

我有完全相同的代码,但输出是这样的:

/**
* 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 'readable' 被调用了两次:
  • 整个回调被调用了 3 次。需要您的建议。

最佳答案

为每个通过的 block 抛出“可读”事件,有时会包含一个杂散的 0。我相信这会发生在你的情况下,因为你的 console.log 行正在获取聚合的“body”值而不是单个“ block ”,您两次都看到 230。 (它返回 230,然后返回 0,但每次总计为 230)。要获取总数据,您只需要连接在“结束”回调中调用的所有 block 。看看这能给你带来什么:

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 个调用。 (当我在我的代码中运行你的确切代码时,由于我上面解释的原因,我得到了多个“ block ”行,但我只得到了一组,只有一个“主体”行。)这是一个更大的测试程序的一部分吗?如果是这样,也许它在其他循环中被调用了 3 次?或者它可能会导致页面笨拙地刷新或重定向几次并发送未发出“结束”信号的 header 。我只是不太了解此函数在 NodeJS 中的工作原理,无法解决此类异常问题。

关于javascript - Http 请求在主体中返回比预期更多的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30745475/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com