【问题标题】:Angular how to get file from APIAngular如何从API获取文件
【发布时间】:2021-12-13 10:50:08
【问题描述】:

我有返回 PDF 文件的 API,但在 Angular 中,当我调用它时会出现此错误

Http failure during parsing for http://localhost:1234/hebaback/public/api/download-report-20
error: SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: '%PDF-1.3\n%�߬�\n3 0 obj\n<</Type /Page\n/Parent 1 0 R\n…1728F9DC34CF5EC66FE> ]\n>>\nstartxref\n2887591\n%%EOF'

功能简单

downloadReport(id: any): Observable<any> {
    return this._HttpClient.get(`http://localhost:1234/hebaback/public/api/download-report-${id}`)
}

我确定错误来自 Angular,因为我在 postman 中尝试过 API 并且效果很好

【问题讨论】:

    标签: angular


    【解决方案1】:

    您需要在请求options 中传递responseType,以便Angular HttpClient 正确解析响应。默认情况下,Angular 需要 JSON 响应,因此您会收到此错误。

    如果服务器返回blob,则将其添加到 responseType。它还支持textarrayBuffer以获得更大的灵活性,因此请相应地配置responseType

    return this._HttpClient.get(`http://localhost:1234/hebaback/public/api/download-report-${id}`, {responseType : 'blob'})
    

    更多详情:https://angular.io/api/common/http/HttpClient#get

    【讨论】:

    猜你喜欢
    • 2020-12-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2021-10-08
    • 2019-01-08
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多