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

Node.js中转发外部API的octet-stream数据遇实现难题求助

解决Node.js中转octet-stream格式二进制数据的问题

修复后的基础版代码

const downloadCertificate = catchAsync(async (req, res) => {
  // 核心:指定responseType为arraybuffer,获取原始二进制数据
  const { headers, data } = await axiosInstance.get(`/certificates/${req.params.txId}`, {
    responseType: 'arraybuffer'
  });

  res.set({
    'Content-Type': headers['content-type'],
    'Content-Disposition': headers['content-disposition'],
    'Content-Length': headers['content-length']
  });
  
  // 直接发送二进制Buffer
  res.end(Buffer.from(data));
});

关键修复点说明

  • 之前的代码没指定responseType,axios默认会把响应解析成字符串或JSON,直接破坏了octet-stream的二进制结构,事后转Buffer也无法恢复原始数据。设置responseType: 'arraybuffer'后,axios会返回未经过任何解析的原始二进制数据。
  • 删掉了accept-ranges头,这个头是当前服务器用来告知客户端自身支持断点续传的,直接转发外部API的该头会误导客户端,无保留必要。
  • 用res.end()代替res.send()发送二进制数据,res.send()会自动处理编码和内容类型,可能干扰二进制数据的正确传输。

大文件优化方案:流式传输

如果要转发的是大文件,用流式传输更节省内存、性能更优:

const downloadCertificate = catchAsync(async (req, res) => {
  const response = await axiosInstance.get(`/certificates/${req.params.txId}`, {
    responseType: 'stream'
  });

  res.set({
    'Content-Type': response.headers['content-type'],
    'Content-Disposition': response.headers['content-disposition'],
    'Content-Length': response.headers['content-length']
  });

  // 直接把外部API的响应流pipe到客户端响应,无需加载整个文件到内存
  response.data.pipe(res);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:55:30