黑色pdf正在从nodejs Nestjs下载

问题描述 投票:0回答:1

我有提供 pdf 服务的第三方 api,当我直接从邮递员或雷霆客户端点击该 url 时,它会提供 pdf 文件,效果完美。

点击此网址时,我正在设置这些标头

Accept: */*
User-Agent: Thunder Client (https://www.thunderclient.com)
x-api-key: my_key
Content-Type: application/pdf
Accept: application/pdf

现在我已经将此 api 封装在我的 Nodejs API 中,所以我已经使用了

控制器

@Get("generate")
  async generate(@Res() res: any): Promise<any> {
    try {
      const pdfData = await this.myService.generate();

      res.setHeader('Content-Type', 'application/pdf');
      res.setHeader('Accept', 'application/pdf');

      // Convert the Axios response data to a readable stream
      const readableStream = new Readable();
      readableStream.push(pdfData.data);
      readableStream.push(null); // Signals the end of the stream

      // Stream the PDF data as the response
      readableStream.pipe(res);

这是服务

async getLabelPdf(refId: string): Promise<any> {
    const url = `url`;
    const headers = {
      "x-api-key": "my_key",
      "Content-Type": "application/pdf",
      "Accept": "application/pdf"
    }
    return axios.get(url, { headers, responseType: "blob" });
  }

但这会下载黑色pdf。

有什么解决办法吗?

node.js stream nestjs blob
1个回答
0
投票

这对我有用

const pdfStream = await this.getLabelPdf();

res.setHeader('Content-Disposition', 'inline; filename="thunder-file.pdf"');
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Accept', 'application/pdf');

// Pipe the PDF stream directly to the Express response
pdfStream.pipe(res);

async getLabelPdf(): Promise<any> {
    const url = `url`;
    const headers = {
      "x-api-key": "my_key",
      "Content-Type": "application/pdf",
      "Accept": "application/pdf"
    }
    return axios.get(url, { headers, responseType: "stream" }).then((res) => res.data);
  }
© www.soinside.com 2019 - 2024. All rights reserved.