【问题标题】:how can superagent and nock work together?superagent 和 nock 如何协同工作?
【发布时间】:2013-01-19 07:13:13
【问题描述】:

在 node.js 中,我无法让 superagent 和 nock 一起工作。如果我使用请求而不是超级代理,它会完美运行。

这是一个简单的例子,superagent 无法报告模拟数据:

var agent = require('superagent');
var nock = require('nock');

nock('http://thefabric.com')
  .get('/testapi.html')
  .reply(200, {yes: 'it works !'});

agent
  .get('http://thefabric.com/testapi.html')
  .end(function(res){
    console.log(res.text);
  });

res 对象没有“文本”属性。出了点问题。

现在如果我使用请求做同样的事情:

var request = require('request');
var nock = require('nock');

nock('http://thefabric.com')
  .get('/testapi.html')
  .reply(200, {yes: 'it works !'});

request('http://thefabric.com/testapi.html', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body)
  }
})

模拟的内容显示正确。

我们在测试中使用了 superagent,所以我宁愿坚持下去。有谁知道如何让它工作?

非常感谢, 泽维尔

【问题讨论】:

    标签: javascript node.js request superagent nock


    【解决方案1】:

    我的假设是 Nock 以 application/json 作为 mime 类型进行响应,因为您使用 {yes: 'it works'} 进行响应。查看 Superagent 中的 res.body。如果这不起作用,请告诉我,我会仔细查看。

    编辑:

    试试这个:

    var agent = require('superagent');
    var nock = require('nock');
    
    nock('http://localhost')
    .get('/testapi.html')
    .reply(200, {yes: 'it works !'}, {'Content-Type': 'application/json'}); //<-- notice the mime type?
    
    agent
    .get('http://localhost/testapi.html')
    .end(function(res){
      console.log(res.text) //can use res.body if you wish
    });
    

    或者...

    var agent = require('superagent');
    var nock = require('nock');
    
    nock('http://localhost')
    .get('/testapi.html')
    .reply(200, {yes: 'it works !'});
    
    agent
    .get('http://localhost/testapi.html')
    .buffer() //<--- notice the buffering call?
    .end(function(res){
      console.log(res.text)
    });
    

    现在任何一个都可以工作。这就是我相信正在发生的事情。 nock 没有设置 mime 类型,并且假定为默认值。我假设默认值为application/octet-stream。如果是这种情况,superagent 不会缓冲响应以节省内存。你必须强制它缓冲它。这就是为什么如果您指定一个 mime 类型(无论如何您的 HTTP 服务应该这样做),superagent 知道如何处理 application/json 以及为什么您可以使用 res.textres.body(解析 JSON)。

    【讨论】:

    • 感谢您的回答! res.body 为空,整个 res 对象包含默认结构,但模拟内容不在其中。我想这不是 mime 类型的问题。
    • 好的,我会试试这个,看看我想出了什么。
    猜你喜欢
    • 2020-01-17
    • 2021-12-09
    • 2019-04-21
    • 2014-08-05
    • 2020-01-14
    • 2012-12-21
    • 2018-07-08
    • 2012-11-30
    • 1970-01-01
    相关资源
    最近更新 更多