如何向AWS API Gateway的GET端点传递查询参数以调用Lambda函数
问题说明
我有一个简单的Lambda函数,功能是返回传入的event对象。在AWS Lambda测试环境中测试时,可以正常返回event.body.url和event.body.webpSupport,运行结果符合预期。
测试用例
{ "body": { "url": "https://someURL.com", "webpSupport": true } }
测试返回结果
Test Event Name test Response { "url": "https://someURL.com", "webpSupport": true }
我不清楚如何将上述参数传递到预发环境的API Gateway地址https://8fjr1z62c4.execute-api.us-east-1.amazonaws.com/foo。目前可查的官方文档都是改版前的旧界面说明,指引中提到需要添加URL查询字符串参数,但新版界面找不到对应入口。
CloudWatch报错日志
{ "errorType": "TypeError", "errorMessage": "The \"url\" argument must be of type string. Received undefined", "code": "ERR_INVALID_ARG_TYPE", "stack": [ "TypeError [ERR_INVALID_ARG_TYPE]: The \"url\" argument must be of type string. Received undefined", " at validateString (internal/validators.js:124:11)", " at Url.parse (url.js:170:3)", " at Object.urlParse [as parse] (url.js:157:13)", " at dispatchHttpRequest (/var/task/node_modules/axios/lib/adapters/http.js:91:22)", " at new Promise (<anonymous>)", " at httpAdapter (/var/task/node_modules/axios/lib/adapters/http.js:46:10)", " at dispatchRequest (/var/task/node_modules/axios/lib/core/dispatchRequest.js:52:10)", " at async Promise.all (index 0)", " at async Runtime.exports.handler (/var/task/index.js:4:28)" ] }
解决方法
问题根因
你在Lambda控制台测试用的event是自定义的结构化格式,但API Gateway默认传给Lambda的event结构和该格式不同,参数不会默认挂载到event.body下,所以取值为undefined触发报错。
场景1:沿用JSON请求体传参(和测试用例格式一致)
无需额外配置API Gateway参数,直接按以下方式调用即可:
- 请求方法用POST
- 请求头添加
Content-Type: application/json - 请求体填入测试用例中的JSON结构
- 调用后Lambda可直接从
event.body取到对应参数
场景2:用URL查询字符串传参
新版API Gateway控制台配置步骤:
- 打开对应API Gateway实例的详情页,左侧导航栏选择「资源」
- 选中你需要配置的
/foo路由,点击页面上方的「方法请求」按钮 - 下拉页面找到「URL 查询字符串参数」板块,点击「添加查询字符串」,依次创建
url和webpSupport两个参数,可根据业务需要勾选「必填」选项 - 配置完成后点击页面顶部的「部署API」,选择你的预发部署阶段后提交,配置即可生效
- 生效后可直接通过GET请求调用:
https://8fjr1z62c4.execute-api.us-east-1.amazonaws.com/foo?url=https://someURL.com&webpSupport=true
- 注意:用查询字符串传参时,Lambda需要从
event.queryStringParameters字段取值,不能再从event.body取值。
校验建议
可以在Lambda函数代码的最开头打印完整的event对象,通过CloudWatch日志确认API Gateway传递的参数结构,避免取值字段错误。
内容的提问来源于stack exchange,提问作者Matthew Kaye
相关产品推荐
相关产品推荐

