簡體   English   中英

Javascript-如何在非200響應中發出警報?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM