如何使用Fetch API读取500状态码响应的响应体内容
解决Fetch API读取500响应体内容的问题
问题核心在于:Fetch API的响应体读取方法(比如text()、json())都是异步操作,直接访问response.body无法拿到解析后的内容,必须调用对应解析方法并等待其执行完成。
修改你的代码如下,针对500状态的响应做异步读取处理:
return fetch(url, options) .then((response) => { if(response.status === 200){ return response.text(); } else if(response.status === 500){ // 根据后端返回的格式选择text()或json() return response.text().then(errorContent => { // 弹出自定义错误提示 alert(errorContent); // 可选:将错误抛到catch块统一处理 throw new Error(errorContent); }); } // 处理其他非200/500的异常状态码 else { return response.text().then(otherMsg => { throw new Error(`请求失败:${otherMsg}`); }); } }) .catch((error) => { throw error; })
额外注意
- 如果后端返回的是JSON格式错误信息(例如
{"errorMsg":"文件下载失败"}),把response.text()替换为response.json(),然后读取对应字段,比如errorContent.errorMsg。 - 确保Spring Boot后端返回500响应时,正确设置
Content-Type响应头:文本格式设为text/plain,JSON格式设为application/json,否则前端解析会失败。
内容的提问来源于stack exchange,提问作者Thulasi
相关产品推荐
相关产品推荐

