简体   繁体   中英

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. 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? 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. When I copy paste the same static object into Postman it works fine. Does anyone know why body:request is being read as an array of requests? Seems that is the reason for the error, because it is expecting an object in the request, not an array of objects

Replacing

    body: request,

with

body: JSON.stringify(request),

seemed to fix it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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