【问题标题】:How do I send binary buffer in Nock Get request?如何在 Nock Get 请求中发送二进制缓冲区?
【发布时间】: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.dataundefined
  • 我在这里创建了一个sn-p:github.com/nock/nock/issues/1510

标签: javascript smartsheet-api nock


【解决方案1】:

默认情况下,Smartsheet API 始终返回 JSON。我不熟悉 nock 库,但这似乎是如何处理响应的问题。如果您在这里没有听到,您可能想在他们的Github 上打开一个问题来询问它。 我确实在您的示例中看到您的 URL 是 https://api.smartsheet.com/2.0/sheet/ Smartsheet API 对请求中的名称使用复数形式,因此对于 List Sheets 请求,它应该是 https://api.smartsheet.com/2.0/sheets/

【讨论】:

  • 这是我的问题的一个错字。正如你所说,它应该是sheets
猜你喜欢
  • 2021-01-25
  • 1970-01-01
  • 2010-09-06
  • 2011-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-06
相关资源
最近更新 更多