![](/img/trans.png)
[英]JavaScript XHR - get raw response data on non-200 status if responseType was set as json
[英]Javascript - how to have a alert on non-200 response from fetch?
假設我有一些類似的代碼
fetch(url).then().catch
如果響應不是200,如何使窗口顯示警報? 因為使用then和catch時它們處於各自的上下文中,所以我無法執行通常的“ window.alert”
因為使用then和catch時它們處於各自的上下文中,所以我無法執行通常的“ window.alert”
你當然可以。
收到非200響應時發出警報?
您確定那是您想要的嗎? 還有其他2xx
狀態代碼也可以。
試試這樣的東西...
fetch(url).then((res) => {
if (!res.ok) {
throw new Error('Response not OK', res);
}
return res;
}).then(/* your then handler */).catch((e) => {
alert('There was an error!!');
});
另請參閱: https : //developer.mozilla.org/zh-CN/docs/Web/API/Response/ok
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.