amazon-web-services - 如何在 AWS Lambda 中获取 HTTP 方法?

标签 amazon-web-services aws-lambda aws-api-gateway http-method

在 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/

相关文章:

javascript - AWS API Gateway Websocket Api - 向所有连接的客户端广播消息

amazon-web-services - "DependsOn": [] means in cloudformation 是什么意思

amazon-web-services - AWS CodeBuild 无法使用 CD 命令

python - 使用 Python 在 Lambda 中处理 S3 桶触发事件

node.js - 使用 Promise 返回 lambda 处理函数

amazon-web-services - API Gateway GET/PUT 大文件到 S3

amazon-web-services - 将无服务器应用程序部署到Docker

c# - 如何使用 C# ASP.NET Core 应用程序通过 Elastic Beanstalk 设置对特定文件夹的权限?

amazon-web-services - 如何使用 Elastic Beanstalk 自动执行 EBS 加密

aws-api-gateway - 向 VTL 中的对象添加键/值对(用于 API 网关)