AWS Lambda测试KeyError问题排查及事件JSON配置咨询
解决Lambda KeyError(缺少'httpmethod')及测试事件格式
核心问题修复
你遇到的KeyError: 'httpmethod'是因为API Gateway传递给Lambda的事件中,HTTP方法的键是大写的httpMethod,而非小写的httpmethod。直接把代码里的event['httpmethod']改成event['httpMethod']就能解决这个错误。
测试用的正确JSON事件格式
GET请求(打开index.html/confirm.html)
{ "httpMethod": "GET", "path": "/", "headers": { "Content-Type": "text/html" } }
如果是请求confirm.html,把path字段改成/confirm即可。
POST请求(提交表单到DynamoDB)
如果是表单提交(application/x-www-form-urlencoded格式),用以下事件结构:
{ "httpMethod": "POST", "path": "/", "headers": { "Content-Type": "application/x-www-form-urlencoded" }, "body": "username=tejas&email=tejas@example.com", "isBase64Encoded": false }
如果是JSON格式的请求,调整Content-Type和body字段:
{ "httpMethod": "POST", "path": "/", "headers": { "Content-Type": "application/json" }, "body": "{\"username\":\"tejas\",\"email\":\"tejas@example.com\"}", "isBase64Encoded": false }
额外排查点
- 确保API Gateway和Lambda使用Lambda Proxy集成:只有这种模式会自动将完整请求元数据(包括
httpMethod)传入Lambda的event参数。如果是非代理集成,需要在API Gateway的集成请求中手动添加映射规则,把HTTP方法映射到event['httpMethod']。 - 检查部署配置:如果用Serverless Framework或AWS SAM,确认配置文件中开启了proxy集成。比如SAM的
AWS::Serverless::Api资源需设置Integration: LambdaProxy。
内容的提问来源于stack exchange,提问作者Tejas Bhosale
相关产品推荐
相关产品推荐

