![](/img/trans.png)
[英]How do I handle an API response with useState to update a state?
[英]How do I handle this API response in Javascript?
我收到了一个 API 错误,我想要 JSON 。
我目前正在处理这样的响应:
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
})
将响应返回为 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\",↵ …"
有什么方法可以将其正确解析为 JSON?
似乎响应无效 JSON 并以纯文本/html 形式返回。 也许看看返回的 header 看看实际的Content-Type
是什么?
如果您想要更清晰的响应,您可以删除response.text
中的大面积空白。
您使用的 API 是否支持 JSON 响应? 您能否在请求 JSON 响应的请求中添加 header ?
我能够通过将字符串解析为 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.