后端从第三方获取PDF存S3正常,但REST API返回客户端为空的问题
问题原因及解决方案
核心原因:Express res.send() 处理 ArrayBuffer 时的隐式转换导致数据损坏
你从第三方接口获取的 pdf 是ArrayBuffer类型,能正常存到S3说明数据本身没问题,但用 res.send(pdf) 返回客户端时,Express的send()方法会对非Buffer/字符串/对象的类型做自动转换,把ArrayBuffer转成了字符串,直接破坏了PDF的二进制结构,最终客户端拿到的就是无效的空文件。
修复方案
把ArrayBuffer转换成Node.js的Buffer类型,再用res.end()发送(res.end()更适合纯二进制数据场景),同时建议加上Content-Length头让客户端准确识别数据大小:
修改 /download 接口代码:
app.post("/download", async (req, res) => { const token = 'abcde-secret-token'; const pdfArrayBuffer = await getReportFromThirdParty(token); await saveToS3(pdfArrayBuffer) // 将ArrayBuffer转换为Buffer const pdfBuffer = Buffer.from(pdfArrayBuffer); res.contentType("application/pdf"); res.setHeader('Content-Length', pdfBuffer.length); return res.end(pdfBuffer); });
额外验证点
- Postman测试时,确保把响应类型切换为
Binary(在Postman的「Response」面板可设置),避免Postman自动解析导致显示异常。 - 也可以尝试用
res.send(Buffer.from(pdfArrayBuffer)),但res.end()对二进制数据的处理更直接。
内容的提问来源于stack exchange,提问作者Moyshe Zuchmir
相关产品推荐
相关产品推荐

