首页 > 解决方案 > Javascript - 如何对 fetch 的非 200 响应发出警报?

问题描述

假设我有一些代码

fetch(url).then().catch

如果响应不是 200,如何使窗口显示警报?因为 then 和 catch 他们在他们自己的上下文中所以我不能做通常的“window.alert”

标签: javascriptjquery

解决方案


因为 then 和 catch 他们在他们自己的上下文中所以我不能做通常的“window.alert”

你当然可以。

对 fetch 的非 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/en-US/docs/Web/API/Response/ok


推荐阅读