You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 10:24:01