how can superagent and nock work together?

谁说胖子不能爱 提交于 2019-12-03 06:00:46

My presumption is that Nock is responding with application/json as the mime type since you're responding with {yes: 'it works'}. Look at res.body in Superagent. If this doesn't work, let me know and I'll take a closer look.

Edit:

Try this:

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
});

or...

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)
});

Either one works now. Here's what I believe is going on. nock is not setting a mime type, and the default is assumed. I assume the default is application/octet-stream. If that's the case, superagent then does not buffer the response to conserve memory. You must force it to buffer it. That's why if you specify a mime type, which your HTTP service should anyways, superagent knows what to do with application/json and why if you can use either res.text or res.body (parsed JSON).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!