【发布时间】:2019-04-19 22:55:01
【问题描述】:
- Nock 版本:^10.0.4
下面的请求总是以字符串形式返回response。我需要 JSON 格式。现在我无法获得res.data(返回未定义),但我可以看到res 作为字符串。
如何获取 JSON 格式的响应?
这是我的要求:
nock('https://api.smartsheet.com/2.0/sheets/')
.defaultReplyHeaders({
"accept-encoding":"gzip, deflate",
"accept": "application/json",
"content-type": "application/json"
})
.get('/')
.reply(200, {"data" : "test"});
- 我尝试使用 JSON.parse({"data": "test"),它仍然返回 String 作为响应。
- 我也试过了
const buffer = Buffer.from(JSON.stringify({data: 'test'}));
const compressed = zlib.gzipSync(buffer);
nock('https://api.smartsheet.com/2.0/sheets/')
.defaultReplyHeaders({
"accept-encoding":"gzip, deflate",
"accept": "application/json",
"content-type": "application/json"
})
.get('/', compressed)
.reply(200, () => compressed);
但我不知道如何在 nock 中发送二进制缓冲区。
如何在 Get 请求中发送二进制缓冲区?
请求代码:
this.smartsheet = SmartsheetClient({
accessToken: this.config.get('smartsheet.oauth_token'),
});
const [getError, sheets] = await this.to(this.smartsheet.sheets.listSheets());
if (getError) {
throw new this.Doh('Fail to get sheets', getError);
}
return sheets.data;
【问题讨论】:
-
我不熟悉 nock 库,但我认为您不一定需要发送二进制缓冲区,您可能只需将 JSON 数据标头添加到 defaultReplyHeaders 以便任何消耗api 知道将数据解释为 JSON。
-
我试过了,但它不起作用。它总是将响应作为一个完整的字符串返回。我真的很确定,
accept-encoding会以不同的格式转换响应。 -
请发布一个调用 nocked 端点的代码示例。它也可能是由请求库的配置引起的。
-
我已经添加了请求代码。就我而言,尝试访问
sheets.data是undefined。 -
我在这里创建了一个sn-p:github.com/nock/nock/issues/1510
标签: javascript smartsheet-api nock