json - Angular:HttpClient 错误,响应为空 200/201(总是调用 JSON.parse (""))

标签 json angular

使用 Angular 时 HttpClient post ,似乎默认是将响应视为 JSON 字符串。当响应正文为空字符串时,即使对于 201 响应,这也会导致错误 ""失败 JSON.parse() .

解决方法是指定responseType: "text"作为附加选项,以便空体不被视为错误。

但是,API 端点确实返回了 JSON 格式的错误描述 请求失败(即成功时为空,错误时为 JSON)。

你如何构建HttpClient post这样我就可以在失败时取回错误消息对象并且成功不算作错误?

例如。:

.subscribe(() => {
    // do something for success, no return object as the body is empty
  , error => {
    // do something with the returned error object
    // right now success is still counted as an error due to the issue above
  }
);

最佳答案

返回响应代码 200 的服务器或 201带有 响应主体和 Content-Type指定为 application/json配置错误,因为空字符串不是有效的 JSON。
正如 OP 所示,指定 responseType: "text"修复了错误,因为空主体没有被解析为 JSON。
解决方法是继续使用 responseType: "text"并检查响应正文是否为空。如果响应体不为空,则调用 JSON.parse(response) .
例子

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';


type HttpOptions = {
  headers?: HttpHeaders | { [header: string]: string | string[]; };
  observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; };
  reportProgress?: boolean; responseType?: "json" /* or "text" as "json" */;
  withCredentials?: boolean;
}

let get_http_options_text = (): HttpOptions => {
  return {
    headers: {'Content-Type': 'text/plain'},
    observe: "body",
    responseType: "text" as "json",  // @see https://github.com/angular/angular/issues/18586
    withCredentials: true
  }
}


@Injectable()
export class MyHttpService {

  constructor(private http: HttpClient) {}

  public post_body_as_string(url: string, body: any, http_params: HttpParams = null):
    Observable<any> {

    let options = get_http_options_text();
    if (http_params != null) {
      options['params'] = http_params;
    }

    return this.http.post<string>(url, body, options).pipe(
      map(response => {
        if (response !== '') {
          return JSON.parse(response);
        } else {
          return {}
        }
      })
    );
  }
}

关于json - Angular:HttpClient 错误,响应为空 200/201(总是调用 JSON.parse ("")),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57404556/

相关文章:

javascript - NSData dataWithContentsOfUrl 需要 javascript

angular - @NgModule 是新的吗?

node.js - 不允许加载本地资源 - Chrome 上出现错误,Angular 应用程序在生产构建后未运行

json - jq 以不同的方式对 KEY 和 VALUES 进行排序 - 如何以相同的顺序枚举它们?

javascript - 如何使用 JSON.parse() 的输出作为 HTML 图表数据字段的输入?

java - 无法从 JSON 字符串实例化类型的值;没有单字符串构造函数/工厂方法

c++ - 用qml ListView显示Json数据

Angular 4选择禁用不起作用

css - Angular 无法在导航到嵌套路由时获取 CSS 文件

javascript - Angular 多步形式路由