Javascript Http请求在正文中返回的数据比预期的多
因为我不能对答案发表评论,所以我想在这里得到一些帮助 我有完全相同的代码,但输出如下:Javascript Http请求在正文中返回的数据比预期的多,javascript,node.js,http,Javascript,Node.js,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 serve
/**
* 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
这让我推断:
- “readable”上的res.on将被调用两次:
- 整个回调被调用了三次。 我需要你的建议
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个电话。(当我在我的代码中运行您的精确代码时,由于我上面解释的原因,我得到了多个“块”行,但我只得到了一个集合,只有一个“主体”行。)这是更大的测试程序的一部分吗?如果是这样的话,可能它在其他循环中被调用了3次?或者,它可能导致一个页面笨拙地刷新或重定向了几次,并且发送的标题没有发出“结束”的信号。我只是不太了解NodeJS中该函数的工作原理,无法解释类似的异常情况。Hi,感谢您这么快的回答,我已经检查了chuck打印,哈哈,我的错。无论如何,我还是担心《三次》的印刷品。我已经用完整的app.js代码编辑了我的帖子