通过AWS API Gateway向Lambda POST数据的参数解析问题求助
问题解决:API Gateway触发Lambda发送SES邮件的参数解析异常
我尝试通过AWS REST API Gateway向Lambda函数POST包含"body":"Test"和"subject":"Test"的JSON数据,Lambda借助AWS SES发送邮件。使用Lambda内置测试事件传入以下扁平结构JSON时,功能完全正常:
{ "subject": "Testing", "body": "Testing" }
但通过Postman POST相同JSON时,出现subject: undefined、body: { "subject":"Testing", "body":"Testing" }的异常。
问题原因
对比Lambda接收的event结构发现:
- Lambda内置测试传入的是扁平结构参数,
subject和body直接在event根节点 - API Gateway转发的Postman请求参数,会被包裹在event的
body字段中,且该字段是JSON字符串格式,不是直接的对象
解决方案
在Lambda代码中添加JSON.parse(param.body)解析请求体字符串,将其转为可直接读取的对象。修复后的可运行Lambda代码如下:
var aws = require('aws-sdk'); var ses = new aws.SES({ region: 'eu-west-2' }); exports.handler = (event) => { sendMail(event); }; async function sendMail(param) { let email = JSON.parse(param.body); const emailParams = { Destination: { ToAddresses: ["你的目标邮箱"], }, Message: { Body: { Text: { Data: email.body }, }, Subject: { Data: email.subject }, }, Source: "你的发件邮箱", }; try { let response = await ses.sendEmail(emailParams).promise(); console.log("邮件发送成功!"); console.log("subject:", email.subject); console.log("body:", email.body); console.log("传入参数:", param); return response; } catch (e) { console.log("邮件发送失败!", e); console.log("subject:", email.subject); console.log("body:", email.body); console.log("传入参数:", param); } }
适配后的测试用例
- Lambda内置测试事件JSON(模拟API Gateway传入的结构):
{ "body": { "subject": "New Test", "body": "New test body" } }
- Postman测试请求JSON:
{ "subject": "Testing", "body": "Testing" }
内容的提问来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

