我正在嘗試從服務器獲取資料,并且我想嘗試將回應正文決議為 json,如果失敗將其作為純文本回傳
fetch(`/devapi/${url}`, {
method: 'GET',
headers: new Headers({
Authorization: `Bearer ${localStorage.getItem("token")}`,
}),
})
.then((res) =>
res
.json()
.then((res) => res?.body?.data || res?.body || res)
.catch((err) => res.text())
)
.then((val) => console.log(val));
當回應不是有效的 json 時,res.text()會呼叫十個,但似乎呼叫.text()after.json會導致錯誤
Failed to execute 'text' on 'Response': body stream already read
uj5u.com熱心網友回復:
您可以克隆回應,然后在錯誤處理程式中使用它:
嘗試這個:
fetch(`/devapi/${url}`, {
method: 'GET',
headers: new Headers({
Authorization: `Bearer ${localStorage.getItem("token")}`,
}),
})
.then((res) => {
const clone = res.clone();
return res
.json()
.then((res) => res?.body?.data || res?.body || res)
.catch((err) => clone.text())
})
.then((val) => console.log(val));
或使用 XHR 并在 a 中處理回應try/catch:
const xhr = new XMLHttpRequest();
xhr.open('POST', `/devapi/${url}`, true);
xhr.setRequestHeader('Authorization', `Bearer ${localStorage.getItem("token")}`);
xhr.onload = function() {
let res;
try {
res = JSON.parse(xhr.response);
} catch (err) {
res = xhr.responseText;
}
console.log(res);
};
xhr.send();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/528582.html
上一篇:如何解決“重復鍵錯誤集合:xxxxxxx.usersindex:name_1dupkey:{name:null}”
