【问题标题】:Nodejs: Unable to get response body when working with vows and nodejs http moduleNodejs:使用 vows 和 nodejs http 模块时无法获取响应正文
【发布时间】:2012-05-05 16:05:05
【问题描述】:

我在玩 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 和 v0.6.2

【问题讨论】:

    标签: node.js testing vows


    【解决方案1】:

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

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

    还请注意,您可以拥有任意数量的块,而不仅仅是一个 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));
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 2022-01-18
      • 2018-05-17
      • 2015-03-29
      • 2016-08-02
      • 1970-01-01
      相关资源
      最近更新 更多