如何返回对象而不是string与诺克反应?
当我使用nock
存根请求时,即使使用'Content-Type': 'application/json'
也会返回String
结果而不是Object
'Content-Type': 'application/json'
:
var response = { success: true, statusCode: 200, body: { "status": "OK", "id": "05056b27b82", } }; Test.BuildRequest(); Test.SendRequest(done); nock('https://someapi.com') // also tried // .defaultReplyHeaders({ // 'Content-Type': 'application/json', // 'Accept': 'application/json' // }) .post('/order') .reply(200, response.body, 'Content-Type': 'application/json', 'Accept': 'application/json');
检查:
console.log(put.response.body); console.log(put.response.body.id);
输出:
{"status":"OK","id":"05056b27b82"} undefined
在代码中,我使用request
模块返回Object
与相同的数据。 我也试过sinon
(不适用于我)和fakeweb
但得到了同样的问题。
我的代码 ,我试图testing:
var request = require('request'); // ... request(section.request, function (err, response, body) { if (err || _.isEmpty(response)) return result(err, curSyndication); //if (_.isString(body)) // body = JSON.parse(body); section.response.body = body; console.log(body.id); // => undefined (if uncomment previous code - 05056b27b82) _this.handleResponse(section, response, body, result); });
并且它在实际的请求中返回一个对象。
PS 。 我可以在响应处理程序中添加下一个代码:
if (_.isString(body)) body = JSON.parse(body);
但是,一些查询返回XMLstring,我不负责这种变化。
Fakeweb :
fakeweb.registerUri({ uri: 'https://someapi.com/order', body: JSON.stringify({ status: "OK", id: "05056b27b82", }), statusCode: 200, headers: { 'User-Agent': 'My requestor', 'Content-Type': 'application/json', 'Accept': 'application/json' } }); Test.SendRequest(done);
相同的结果。
更新:
我阅读了一些使用JSON对象的文章,而没有parsing它(使用nock),所以它应该返回JSON对象,和请求库一样。
你的nockconfiguration没有错,但是你还没有告诉request
将响应parsing为JSON。
从request
方法文档(强调我):
json
– 设置正文,但JSON表示值,并添加Content-type:application / json标题。 另外,将响应主体parsing为JSON。callback参数获取3个参数:
- 适用时出错(通常来自http.ClientRequest对象)
- 一个http.IncomingMessage对象
- 第三个是响应主体( 如果提供了
json
选项,则为 String或Buffer,或者JSON对象 )
所以你需要在你的section.request
对象上设置json
属性为true
:
var request = require('request'); // ... section.request.json = true; request(section.request, function (err, response, body) { //.. });