Angular 8中如何根据响应状态码处理不同格式的接口返回体
问题原因
你的代码存在两个核心问题导致201状态码报错:
- Angular HttpClient默认仅返回响应体内容,无法获取状态码做分支判断
- HttpClient默认将响应类型设为
json,收到201返回的纯文本时会在内部先抛出JSON解析错误,不会进入后续的map处理逻辑
解决方案
调整请求配置获取完整响应对象,自行根据状态码处理不同返回格式:
- 请求配置新增
observe: 'response'获取完整HttpResponse对象(包含状态码、响应体等全量信息) - 请求配置新增
responseType: 'text'统一先按纯文本解析响应,避免框架自动JSON解析报错 - 在
map中按状态码分支处理:200时手动转JSON再走原有转换逻辑,201时直接返回纯文本提示
修改后的代码如下:
this.httpClient.post(url, uploadedFile, { params: httpParams, observe: 'response', responseType: 'text' }).pipe( catchError(err => throwError(err)), map(response => { if (response.status === 200) { const jsonBody = JSON.parse(response.body); return this.transformImportCSVResponse(jsonBody); } else if (response.status === 201) { return response.body; } // 其他状态码可按需扩展处理逻辑 return response.body; }) )
可选优化
如果担心200状态下返回的内容不是合法JSON,可以用try catch包裹JSON.parse逻辑,避免解析异常直接抛出:
if (response.status === 200) { try { const jsonBody = JSON.parse(response.body); return this.transformImportCSVResponse(jsonBody); } catch (e) { // 按需处理JSON解析异常逻辑 throw new Error('返回内容格式异常'); } }
内容的提问来源于stack exchange,提问作者Girija Sankar Panda
相关产品推荐
相关产品推荐

