Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http failure during parsing for http... while downloading pdf file

I am new to angular and I have been struggling to figure out how to download a file, in my case a pdf file. This is the error I get:

Http failure during parsing for https://url...

In the debug console of the browser the is also an error:

SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse

Actually I am downloading a pdf file. Here is how my http call looks like:

  protected get<T>(url: string, params: any, defaultResult: T): Observable<T> {
    return this.httpClient.get<T>(url, {
    headers: myHeader,
    params: params
})
  .pipe(catchError(this.handleError(defaultResult))
  );

} How

like image 425
edmond Avatar asked Dec 14 '22 17:12

edmond


1 Answers

Since you are passing back a blob of data rather than JSON but not letting the httpclient know how to parse it back, angular is trying to parse response back as a JSON which is the default path.

Here is documentation from the angular website:

request(first: string | HttpRequest<any>, url?: string, options: {
    body?: any;
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: HttpObserve;
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType?: 'arraybuffer' | 'blob' | 'json' | 'text';
    withCredentials?: boolean;
} = {}): Observable<any>

responseType:

In addition to configuring request parameters such as the outgoing headers and/or the body, the options hash specifies two key pieces of information about the request: the responseType and what to observe. The responseType value determines how a successful response body will be parsed. If responseType is the default json, a type interface for the resulting object may be passed as a type parameter to request().

So in your case try:

    protected get<T>(url: string, params: any, defaultResult: T): Observable<any> {
        return this.httpClient.get(url, {
        headers: myHeader,
        params: params,
        responseType: 'blob'
    })
      .pipe(catchError(this.handleError(defaultResult))
      );

more info:

httpclient

documentation

Similar question Angular HttpClient "Http failure during parsing"

like image 116
abann sunny Avatar answered Dec 28 '22 09:12

abann sunny