AWS Lambda+API Gateway返回docx文档异常问题求助
问题解决:API Gateway触发Lambda返回docx文档异常
一、初始响应头为application/json的原因及解决
当使用API Gateway触发Lambda时,如果最初响应头始终是application/json,核心原因是未启用Lambda代理集成:
- 若使用非代理集成,API Gateway会默认把
application/json作为响应类型,且需要手动在集成响应中配置响应头和转换模板。 - 解决方式:在API Gateway的集成设置中切换为Lambda代理集成,此模式下API Gateway会完全遵循Lambda返回的
headers、statusCode等参数,无需额外配置响应模板。
二、Word提示“不可读内容”的原因及修复
你遇到的文档内容是base64字符串的问题,根源在于使用第三方js-base64库的encode方法处理Buffer,而非Node.js原生的Buffer转换方式。
问题分析
Lambda的isBase64Encoded: true参数要求body是标准的base64编码字符串,API Gateway会将其解码为二进制流返回给客户端。但js-base64的encode方法对Buffer的处理逻辑与Node.js原生转换存在差异,导致API Gateway无法正确解码,最终直接返回base64文本内容,而非二进制docx文件。
修复步骤
- 移除
js-base64依赖(无需额外安装该库); - 将
body: encode(buffer)替换为body: buffer.toString('base64'),使用Node.js Buffer原生的base64转换方法。
修复后的完整代码
const AWS = require('aws-sdk'); const { Document, Packer, Paragraph, TextRun } = require("docx"); const dynamoDb = new AWS.DynamoDB.DocumentClient(); exports.handler = async (event) => { const params = { TableName: 'table-name', Key: { 'id': 'item-key', }, }; const dynamoDbResult = await dynamoDb.get(params).promise(); const data = dynamoDbResult.Item; const doc = new Document({ sections: [ { properties: {}, children: [ new Paragraph({ children: [ new TextRun(data.projectName), new TextRun({ text: data.clientEmail1, bold: true }), ] }) ] } ] }); const buffer = await Packer.toBuffer(doc); return { statusCode: 200, headers: { 'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'Content-Disposition': 'attachment; filename="your_file_name.docx"' }, body: buffer.toString('base64'), isBase64Encoded: true }; }
验证要点
确保API Gateway已启用Lambda代理集成,此时客户端请求后会直接收到二进制docx文件,Word可正常打开。
内容的提问来源于stack exchange,提问作者dnd1993
相关产品推荐
相关产品推荐

