You need to enable JavaScript to run this app. 使用axios请求HTTP地址可正常获取PDF但HTTPS地址返回空白PDF是何原因?
优惠活动
大模型
产品
解决方案
定价
更多

使用axios请求HTTP地址可正常获取PDF但HTTPS地址返回空白PDF是何原因?

修复方案

HTTPS场景下获取PDF内容空白的核心原因是Node.js环境下axios对blob类型的响应处理存在兼容缺陷,以及二进制转Buffer的方式错误,可通过以下方案修复:

  • 调整响应类型配置(推荐)
    Node.js环境下blob是浏览器端专属的二进制对象类型,axios在Node.js中返回的blob为模拟对象,直接转Buffer会丢失真实二进制内容。将responseType替换为arraybuffer即可直接生成正确的Buffer,修改后代码如下:
    const data = await axios({
      url: url,
      method: 'get',
      responseType: 'arraybuffer',
      // 可选配置:部分HTTPS站点开启gzip压缩时需开启自动解压
      decompress: true
    }).then((response) => {
      return Buffer.from(response.data);
    });
    
    return data;
    
  • 保留blob类型的修复方式
    如果业务逻辑需要保留blob类型的响应,不能直接将Blob对象传入Buffer.from,需先读取Blob的ArrayBuffer内容再做转换,正确代码如下:
    const blobData = await axios({
      url: url,
      method: 'get',
      responseType: 'blob',
      decompress: true
    }).then(response => response.data);
    
    const arrayBuffer = await blobData.arrayBuffer();
    return Buffer.from(arrayBuffer);
    
  • 额外排查项
    确认axios全局配置未设置responseEncoding: 'utf8',该配置会强制将二进制响应按UTF-8编码解码,导致PDF内容损坏。

内容的提问来源于stack exchange,提问作者David McIntyre

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 07:48:03