![](/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.