下载pdf文件时解析http时Http失败 [英] Http failure during parsing for http... while downloading pdf file

查看:138
本文介绍了下载pdf文件时解析http时Http失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对angular并不陌生,我一直在努力寻找如何下载文件(以我的情况为pdf文件). 这是我得到的错误:

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

实际上,我正在下载pdf文件.这是我的http调用的样子:

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))
  );

}

推荐答案

由于您要传回的数据不是JSON,而是不让httpclient知道如何解析回数据,因此angular尝试将响应解析为JSON是默认路径.

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.

以下是来自Angular网站的文档:

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和观察内容. responseType值确定如何解析成功的响应正文.如果responseType是默认的json,则可以将结果对象的类型接口作为类型参数传递给request().

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().

因此您可以尝试:

    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))
      );

更多信息:

httpclient

文档

类似的问题 Angular HttpClient解析期间发生Http失败"

这篇关于下载pdf文件时解析http时Http失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆