Angular 4 http throws error on PUT response without body

Viewed 14533

I am using Angular http module v4.4.6. When the Angular application (client) is sending a PUT request (using HttpClient) to the server, and the server responses a status 200 (OK) without any data in body, angular http module throws an HttpErrorResponse.

Is this a proper feature or a bug?
How to handle PUT responses without any data in body?


In Detail:

In recent versions I have used normal Http module and it's method put(). There I need to call res.json() to get the JSON data in body. The put() method returns Observable<Response>.

Now I use the newer HttpClient and it's put() method. This method returns Observable<Object>. It seems that the json() method is called internally and leads to the error I see.

  • Angular client creates PUT request with HttpHeader 'Content-Type': 'application/json'. This results in a HTTP PUT request header Accept:application/json, text/plain, */*).
  • The server answers with status 200 (OK) and without any data in the body.
  • The Angular client receives the answer and throws the error.

HttpErrorResponse {headers: HttpHeaders, status: 200, ... error: error: SyntaxError: Unexpected end of JSON input at .. text: "" headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: ... message: "Http failure during parsing for ... name: "HttpErrorResponse" ok: false status: 200 statusText: "OK" url: ...

2 Answers

@yonexbat, Thanks you are right.

If using ....

const response = this.http.put(url, data, { responseType: 'text'}).toPromise();

... the problem is solved.

The corret code in Angular 7/8 is

const options = {responseType: 'text' as 'json'};
const response = this.http.put(url, data, options).toPromise();

Don't ask why this stupid approach is valid :-/ See link

Related