![](/img/trans.png)
[英]Angular 9 HttpErrorResponse 'JSON.Parse error' while response is OK
[英]Angular: HttpClient error with empty 200/201 response (always calls JSON.parse(""))
在使用 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 {}
}
})
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.