在 AWS Lambda 代码中,如何获取来自 AWS Gateway API 的 HTTP 请求的 HTTP 方法(例如 GET、POST...)?
我从documentation了解到那个 context.httpMethod 是解决方案。
但是,我无法让它发挥作用。
例如,当我尝试添加以下 3 行时:
if (context.httpMethod) {
console.log('HTTP method:', context.httpMethod)
}
进入“microservice-http-endpoint”蓝图的AWS示例代码如下:
exports.handler = function(event, context) {
if (context.httpMethod) {
console.log('HTTP method:', context.httpMethod)
}
console.log('Received event:', JSON.stringify(event, null, 2));
// For clarity, I have removed the remaining part of the sample
// provided by AWS, which works well, for instance when triggered
// with Postman through the API Gateway as an intermediary.
};
我从来没有在日志中记录过任何内容,因为 httpMethod 始终为空 .
最佳答案
context.httpMethod
方法仅适用于模板。因此,如果您想访问 Lambda 函数中的 HTTP 方法,则需要在 API 网关(例如 GET)中找到该方法,转到集成请求部分,单击映射模板,然后添加新的映射模板为 application/json
.然后,选择 application/json
并选择映射模板并在编辑框中输入如下内容:
{
"http_method": "$context.httpMethod"
}
然后,当您的 Lambda 函数被调用时,您应该会在
event
中看到一个新属性。传入调用 http_method
其中包含用于调用该函数的 HTTP 方法。
关于amazon-web-services - 如何在 AWS Lambda 中获取 HTTP 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35252544/