javascript - Javascript - 如何对 fetch 的非 200 响应发出警报?
问题描述
假设我有一些代码
fetch(url).then().catch
如果响应不是 200,如何使窗口显示警报?因为 then 和 catch 他们在他们自己的上下文中所以我不能做通常的“window.alert”
解决方案
因为 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
推荐阅读
- sql - Analysis Services Power Query 编辑器性能
- r - 将数据框转换为矩阵
- vue.js - Vuetify 日期选择器:多个事件指示器
- python - R:R 相当于 numpy 的 .dtype.itemsize 和 .dtype.alignment 数组属性是什么?
- c# - 尝试检查不同工作站的友好操作系统名称
- python - 如果未定义字段,如何跳过渲染文件?
- sql - Oracle SQL - 将列转置为行的新表
- oracle - 包中的函数不返回日期,
- javascript - javascript循环改变其他对象的值
- gridview - 从 Devexpress 中的 GridView 选定行获取列值