简体   繁体   English

如何在 Javascript 中处理此 API 响应?

[英]How do I handle this API response in Javascript?

I'm getting an API error that I would like to have the JSON for.我收到了一个 API 错误,我想要 JSON 。

I'm currently handling the response like this:我目前正在处理这样的响应:

return fetch( 'https://api-prod.corelogic.com/property/' + propertyId + '/avm/thv/thvMarketingStandard', {
  method: "GET",
  headers: {
    Accept: 'application/json',
    Authorization: "Bearer " + token
  },
})
.then(function (resp) {

  console.log(resp)

  if(resp.status === 200 ){

    // Return the response as JSON
    return resp.json();         
  }else{
    return resp.text()
  }

}).then(function (data) {
  console.log(JSON.stringify(data), data.toString())    
  return data
})

Returning the response as JSON was giving me nothing, so I returned it as text and got the following:将响应返回为 JSON 什么也没给我,所以我将其作为文本返回并得到以下信息:

"<root>\n                    {\n                        \"errorCode\": \"429\",\n                        \"message\": \"Quota Exceeded\",\n                        \"description\": \"You have exceeded your daily quota for this application and orders will no longer be processed today. You will be able to resume testing tomorrow.\"\n                    }\n                </root>\n            " – "<root>↵                    {↵                        \"errorCode\": \"429\",↵                        \"message\": \"Quota Exceeded\",↵            …"

Is there any way I can parse this correctly into JSON?有什么方法可以将其正确解析为 JSON?

It appears the response is not valid JSON and is being returned in plaintext/html.似乎响应无效 JSON 并以纯文本/html 形式返回。 Perhaps look at the returned header to see what the actual Content-Type is?也许看看返回的 header 看看实际的Content-Type是什么?

If you want a more clear response you could remove the large areas of whitespace in the the response.text .如果您想要更清晰的响应,您可以删除response.text中的大面积空白。

Does the API you are using support JSON responses?您使用的 API 是否支持 JSON 响应? Could you add a header in your request that asks for a JSON response?您能否在请求 JSON 响应的请求中添加 header ?

I was able to retrieve the JSON by parsing the string as XML:我能够通过将字符串解析为 XML 来检索 JSON:

  .then(function (resp) {

      console.log(resp)

        if(resp.status === 200 ){

            // Return the response as JSON
            return resp.json();         
        }else{
            return resp.text();

        }


    }).then(function (data) {


        if(IsJsonString(data)){
            return data
        }else{
            const parser = new DOMParser();
            const errorXML = parser.parseFromString(data,"text/xml")
            const errorString  = errorXML.getElementsByTagName("root")[0].childNodes[0].nodeValue
            const errorJSON = JSON.parse(errorString as string)
            console.log(errorJSON)
        }

    })

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

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