gpt4 book ai didi

Javascript - 如何对 fetch 的非 200 响应发出警报?

转载 作者:行者123 更新时间:2023-12-03 00:24:24 26 4
gpt4 key购买 nike

假设我有一些代码,例如

fetch(url).then().catch

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

最佳答案

Because with then and catch they are in their own context so I can't do the usual "window.alert"

当然可以。

alert on non-200 response from fetch?

你确定这就是你想要的吗?还有其他 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

关于Javascript - 如何对 fetch 的非 200 响应发出警报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54156054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com