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

Node.js v16中Excel转Blob后Axios获取异常求助

Node.js返回Excel文件Blob,Axios仅获取2字节JSON的解决方案

问题根源

Node.js v16中从node:buffer导入的Blob与浏览器Blob结构不同,Express的res.send()方法处理非Buffer/字符串/流类型的对象时,会自动将其序列化为JSON。你发送的Blob对象被序列化为{}(正好2字节),因此Axios收到的是application/json类型的2字节Blob。

解决方案

无需在服务端创建Blob,直接返回文件Buffer并设置正确的响应头,或者使用Express内置的res.sendFile()方法:

方法1:直接发送Buffer并设置响应头

import fs from 'node:fs';

app.get('/getBlob', (req, res) => {
  const data = fs.readFileSync('./files/test.xlsx');
  // 设置Excel文件的MIME类型
  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  // 可选:设置文件大小,帮助客户端验证
  res.setHeader('Content-Length', data.length.toString());
  res.send(data);
});

方法2:使用res.sendFile简化代码

app.get('/getBlob', (req, res) => {
  const filePath = './files/test.xlsx';
  res.sendFile(filePath, {
    headers: {
      'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    }
  }, (err) => {
    if (err) {
      res.status(500).send('文件读取失败');
    }
  });
});

验证Axios请求

你的Axios代码无需修改,保持responseType: "blob"即可:

axios.get("http://localhost:8000/getBlob", {
  responseType: "blob",
})
.then(response => {
  console.log(response.data); // 现在会显示正确大小的Blob,类型为application/vnd.openxmlformats...
})

为什么之前的Base64尝试无效?

将文件转为Base64后创建Blob,本质还是发送Node的Blob对象,依然会被Express序列化为JSON,因此无法解决问题。核心是要避免在服务端创建Blob后直接发送,改用原始Buffer或sendFile方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:07:27