angular: HttpClient 'Http failure during parsing' error for valid json

I’m submitting a…


[ ] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

Request throws an error when trying to parse a response of "ok" which is considered valid json according to https://jsonlint.com/


request:

    const requestOptions = Object.assign(
      {}, 
      { responseType: 'json' }, 
      { observe: 'body' as HttpObserve }
    );

    this.httpClient.request('GET', './mockjson.json', requestOptions)
    ...

error: "Unexpected token o in JSON at position 0"

Expected behavior

No error should be thrown for a response of "ok"

Minimal reproduction of the problem with instructions

https://embed.plnkr.co/klPNUS/

What is the motivation / use case for changing the behavior?

Environment


Angular version: 4.3.2


Browser:
- [x] Chrome (desktop) version XX
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX
 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 8
  • Comments: 25 (3 by maintainers)

Commits related to this issue

Most upvoted comments

this.http.get(url, {responseType: ‘text’})

it works as well.

Ran into same problem making a put request to my endpoint. I realized I was sending 200 without a response body. Sending status code 204 made angular http 5.2.8 stop complaining. This problem should not be happening even with a 200, but 204 is the correct code for empty responses.

This works for me. Pretty much the same as @mrahhal answer only I also found I had to catch and parse the error as well.

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const clonedRequest = req.clone({
      responseType: 'text'
    });

    return next.handle(clonedRequest)
      .map((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          return event.clone({
            body: JSON.parse(event.body),
          });
        }
      })
      .catch((error: HttpErrorResponse) => {
          const parsedError = Object.assign({}, error, { error: JSON.parse(error.error) });
          return Observable.throw(new HttpErrorResponse(parsedError));
      });
  }

@dyh333
this.http.get(url, {responseType: ‘text’})

it works as well.

Some people may be confusing about this and I’m included, this is the reference for he’s mean : https://angular.io/guide/http#requesting-non-json-data

thank for you @dyh333 and sorry my english too bad.

For those who can not change to a text content type (in my case a POST file upload with content type application/octet-stream, the following seems like a solution:

return this.httpClient.request<File>(req)
			//TODO remove when Angular 4.4 Json parse bug is fixed
			.catch((error: HttpErrorResponse) => this.handleAngularJsonBug(error))
private handleAngularJsonBug (error: HttpErrorResponse) {
		const JsonParseError = 'Http failure during parsing for';
		const matches = error.message.match(new RegExp(JsonParseError, 'ig'));

		if (error.status === 200 && matches.length === 1) {
			// return obs that completes;
			return Observable.empty();
		} else {
			this.log.debug('re-throwing ');
			return Observable.throw(error);		// re-throw
		}
	}

Hi, It works for me to set Headers like let httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', }), responseType: 'text' as 'json' }; Hope it helps.

The date is 11.11.2018 and I am still having the same issue!! Do you guys have any updated solution? Thanks!

Well, now the date is 28.12.2018 and I have just upgraded to 7.1.4 and the issue is still presented. Stunning…

@leojkwan thanks for your comment. I ran into the same issue with Angular 5.2.9.

Agreed, this is a bug. Nice catch.

As a workaround, you can add an interceptor which turns the json request into text and does the JSON.parse itself.

I updated our Http to HttpClient and all strings being returned were giving me ‘Http failure during parsing’. Thanks to mrahhal and jamiemac87, I combined your fixes and Json responses as strings are now working.

I tried my hand at it, came up with this:

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

// Remove when https://github.com/angular/angular/pull/18466 gets merged.

@Injectable()
export class WA18396Interceptor implements HttpInterceptor {
	constructor() { }

	intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
		if (req.responseType == 'json') {
			req = req.clone({ responseType: 'text' });

			return next.handle(req).map(response => {
				if (response instanceof HttpResponse) {
					response = response.clone<any>({ body: JSON.parse(response.body) });
				}

				return response;
			});
		}

		return next.handle(req);
	}
}

Works in my initial tests.

how long before this is fixed and merged?