使用 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/