如何在Fetch中获取响应码与JSON响应,判断数据是否成功发送?
实现数据提交成功的判断逻辑
结合你提到的两种思路,我们可以同时用响应状态码判断和try-catch异常捕获来覆盖所有可能的失败场景,以下是修改后的完整代码:
public async daten_eintragen(): Promise<void> { try { const jsondata = { proasdftName: "tfghtdsddskt", pauctasdfsion: "this.csdfgudfghrrentItemVersio", cosdfasdftName: "mardfddsdfgfdfbvdfdasdfumfghjann", vdon: "this.currentItesdfghdfmVersion", vedor: "this.currentsdfgItemVendor", lde: "this.currentsdfdfgItemFrdgfhamework", proepage: "this.csdfgurrentItedfghmHomepage", nType: "this.cursdfgrentItedfghmIntegration", upe: "this.currentItsdfgfdghemUsage", sL: "this.currentItemSsdfgourcfgheCodeAnpassungen", }; console.log(this.currentItemName); const response = await fetch(this.appConf.apiBaseUrl + "compon", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify(jsondata), }); // 通用成功判断:状态码在200-299之间 if (!response.ok) { // 解析服务器返回的错误信息(兼容JSON或文本格式) const errorDetails = await response.json().catch(() => response.text()); throw new Error(`请求失败:${response.status} ${response.statusText},详情:${JSON.stringify(errorDetails)}`); } // 若业务要求仅200状态码才算成功,可替换为下面的判断 // if (response.status !== 200) { // throw new Error(`请求失败,状态码:${response.status}`); // } const data = await response.json(); console.log("数据提交成功", data); // 这里添加成功后的业务逻辑(如用户提示、页面更新等) } catch (error) { console.error("数据提交失败", error); // 这里处理所有异常情况(如网络中断、跨域拦截、服务器错误等) } }
关键逻辑说明
- try-catch 捕获异常:覆盖网络层面的错误(断网、跨域被浏览器拦截、请求超时)以及JSON解析失败等场景
- 响应状态判断:
response.ok是fetch提供的快捷判断,等价于response.status >= 200 && response.status < 300,适用于大多数REST API的成功场景- 如果你的业务接口要求必须返回200状态码,直接判断
response.status === 200即可
- 错误细节处理:即使是HTTP错误(如400参数错误、500服务器异常),服务器通常会返回错误描述,我们可以尝试解析并抛出,方便调试和给用户提示
- 注意:原代码中定义的
Access-Control-Allow-Origin等头是服务器端需要设置的响应头,前端设置这些头无效,所以直接删除了
内容的提问来源于stack exchange,提问作者Mark Baumann
相关产品推荐
相关产品推荐

