简体   繁体   English

无法使用 node-fetch 解析响应消息

[英]Unable to parse Response message using node-fetch

My goal is to read the message that is returned within the response.我的目标是阅读响应中返回的消息。 I am using node-fetch and the response is gzipped.我正在使用 node-fetch 并且响应被压缩。 This is what I have so far:这是我到目前为止所拥有的:

  const response = await fetch(config.url, {
            method: 'POST',
            body: request,
            headers: {'Content-Type': 'application/json; charset=UTF-8', 'x-tn-api_key':config.key, 'x-tn-api_signature':generateAPISignature()}
          })

    let deserializedResponse = await response.json()

This is what deserializedResponse looks like:这是反序列化响应的样子:

{
  "timestamp": "2021-03-03T22:34:37.362+0000",
  "status": 400,
  "error": "Bad Request",
  "message": "JSON parse error: Cannot deserialize instance of `xyz` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `xyz` out of START_ARRAY token\n at [Source: (PushbackInputStream); line: 1, column: 1]",
  "path": "/a/v1/events"
}

There is json parse error in message field, how can I read the message field?消息字段出现 json 解析错误,如何读取消息字段? Essentially if the call fails, I want to log the message for debugging purposes.本质上,如果调用失败,我想记录消息以进行调试。

Update: I hard coded request object to some static object and still getting the same error.更新:我硬编码请求 object 到一些 static object 并且仍然得到相同的错误。 When I copy paste the same static object into Postman it works fine.当我将相同的 static object 复制粘贴到 Postman 中时,它工作正常。 Does anyone know why body:request is being read as an array of requests?有谁知道为什么 body:request 被读取为请求数组? Seems that is the reason for the error, because it is expecting an object in the request, not an array of objects似乎这是错误的原因,因为它在请求中期望 object,而不是对象数组

Replacing更换

    body: request,

with

body: JSON.stringify(request),

seemed to fix it似乎修好了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM