You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 8中如何根据响应状态码处理不同格式的接口返回体

问题原因

你的代码存在两个核心问题导致201状态码报错:

  1. Angular HttpClient默认仅返回响应体内容,无法获取状态码做分支判断
  2. HttpClient默认将响应类型设为json,收到201返回的纯文本时会在内部先抛出JSON解析错误,不会进入后续的map处理逻辑

解决方案

调整请求配置获取完整响应对象,自行根据状态码处理不同返回格式:

  1. 请求配置新增observe: 'response'获取完整HttpResponse对象(包含状态码、响应体等全量信息)
  2. 请求配置新增responseType: 'text'统一先按纯文本解析响应,避免框架自动JSON解析报错
  3. 在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 15:36:03