我正在调用一个返回PDF文件的外部API,并且我想在我的控制器函数响应中返回这个PDF文件。
在我的控制器类中:
@Get(':id/pdf')
async findPdf(@Param('id') id: string, @Res() res: Response) {
const response = await this.documentsService.findPdf(id);
console.log(response.data);
// this prints the following:
// %PDF-1.5
// %����
// 2 0 obj
// << /Type /XObject /Subtype /Image /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter // /DCTDecode /Width 626 /Height
// 76 /Length 14780>>
// stream
// and go on...
return res
.status(200)
.header('Content-Type', 'application/pdf')
.header('Content-Disposition', response.headers['content-disposition'])
.send(response.data);
}
在我的服务类中:
findPdf(id: string): Promise<any> {
return firstValueFrom(
this.httpService
.get(`/docs/${id}/pdf`)
.pipe(map((response) => response))
.pipe(
catchError((e) => {
throw new BadRequestException('Failed to get PDF.');
}),
),
);
}
但是我在响应中得到了一个空的PDF文件。
内部API调用没有问题,我已经从Postman测试过了,PDF文件是正确的。
我做错了什么?