如何在NodeJS中使用Apollo datasource rest下载PDF文件
解决方法
你当前的代码核心问题是apollo-datasource-rest默认会将响应解析为JSON/普通文本,不会返回二进制格式的响应数据,同时没有针对gzip压缩的二进制文件下载做对应配置。
修正后的代码
import { RequestOptions, RESTDataSource } from 'apollo-datasource-rest'; import * as fs from 'fs'; import * as zlib from 'zlib'; export class DocumentManagementService extends RESTDataSource { async downloadDocument(id: string): Promise<void> { const responseBuffer = await this.get<Buffer>( `/documents/${id}/download`, undefined, { // 指定响应返回二进制Buffer,跳过默认的JSON/文本解析逻辑 responseType: 'buffer', // 自动识别并解压gzip编码的响应 decompress: true, // 可选:添加Accept头明确告知服务端需要PDF格式数据 headers: { 'Accept': 'application/pdf' } } as RequestOptions ); // 直接写入Buffer即可,不需要额外指定binary编码 fs.writeFileSync('test.pdf', responseBuffer); } }
异常兼容方案
如果上述配置生成的PDF仍无法正常打开,可以关闭自动解压后手动处理gzip压缩数据:
const compressedBuffer = await this.get<Buffer>( `/documents/${id}/download`, undefined, { responseType: 'buffer', decompress: false, headers: { 'Accept': 'application/pdf' } } as RequestOptions ); // 手动执行gzip解压得到原始PDF数据 const pdfBuffer = zlib.gunzipSync(compressedBuffer); fs.writeFileSync('test.pdf', pdfBuffer);
内容的提问来源于stack exchange,提问作者Krunal Shah
相关产品推荐
相关产品推荐

