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
相关产品推荐
相关产品推荐

