gpt4 book ai didi

node.js - Node : Unable to get response body when working with vows and nodejs http module

转载 作者:行者123 更新时间:2023-11-28 21:33:28 25 4
gpt4 key购买 nike

我在玩 vows 和 nodejs。

var vows = require('vows');
var http = require('http');
var suite = vows.describe('testing');
var host = 'www.google.com', port = '80', path = '/', method = 'GET';

suite.addBatch({
'A context': {
topic: function(){
http.get({
host: host,
port: port,
path: path,
method: method
}, this.callback);
},
"sample test": function(res, extra){//here extra is just to prevent vows error
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);//It never gets logged
});
console.log('HEADERS: ' + JSON.stringify(res.headers));//it is working
}
}
});

suite.export(module);

但是我无法获取响应正文。我做错了什么。

我正在使用 nodejs v 0.6.6 和 vows v0.6.2

最佳答案

据我所知,当 this.callback 运行时,Vows 似乎没有直接调用测试。它被 processnextTick 延迟。如果非要我猜的话,也许“数据”事件是在那段时间发出的。这意味着在触发所有数据事件之前,您不会绑定(bind)“数据”函数。

但实际上,问题是 Vows 测试应该将像这样的所有异步逻辑分离到 topic 本身。如果你真的想检查测试中的 block ,那么就这样做吧。

另请注意,您可以拥有任意数量的 block ,而不仅仅是单个 data 事件。您可能想要设置流编码,并将数据作为字符串加入。您当前的代码将 Buffer 隐式转换为字符串,这可能会中断多字节字符。

suite.addBatch({
'A context': {
topic: function(){
var cb = this.callback;
var req = http.get({
host: host,
port: port,
path: path,
method: method
});

// Aggregate all chunks before running callback
req.on('response', function(res) {
var chunks = []
res.on('data', function(chunk) {
chunks.push(chunk);
});
res.on('end', function() {
cb(null, res, chunks);
});
});

// Handle connection failures.
req.on('error', cb);
},
"sample test": function(err, res, chunks){
chunks.forEach(function (chunk, i) {
console.log('BODY piece ' + i + ': ' + chunk);
});
console.log('HEADERS: ' + JSON.stringify(res.headers));
}
}
});

关于node.js - Node : Unable to get response body when working with vows and nodejs http module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10463580/

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