首页 > 解决方案 > Angular 4:将响应从 API 转换为 PDF

问题描述

在此处输入图像描述

大家好,我在尝试从 API 转换响应时遇到问题,出现错误

请求正文既不是 blob 也不是数组缓冲区

这是我的代码

应用服务.ts

downloadPDF(id_booking): any {
  let headers = new Headers();
  this.createAuthorizationHeader(headers);
  return this.http.post('https://localhost:1210/v1/user/booking/eticket/'+id_booking, {responseType: ResponseContentType.Blob}, {headers: headers}).map(
  (res) => {
    console.log(res)
    return new Blob([res.blob()], { type: 'application/pdf' })
  })
}

pdf.component.ts

this.appService.downloadPDF(booking._id).subscribe(
    (res) => {
    saveAs(res, "myPDF.pdf"); 
    var fileURL = URL.createObjectURL(res);
    window.open(fileURL);
    }

标签: angulartypescripthttp

解决方案


您的后端当前正在发送一个字符串。

假设您使用的是快递,而不是

res.send(arr)

你应该使用

res.send(buffer);

这将确保发送二进制数据


推荐阅读