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

Amazon web services 如何在AWS Lambda中获取HTTP方法?,amazon-web-services,aws-lambda,aws-api-gateway,http-method,Amazon Web Services,Aws Lambda,Aws Api Gateway,Http Method,在AWS Lambda代码中,如何获取HTTP方法,例如get、POST。。。来自AWS网关API的HTTP请求的安全性 我从上下文中了解到。httpMethod就是解决这个问题的方法 然而,我无法使它工作 例如,当我尝试添加以下3行时: if (context.httpMethod) { console.log('HTTP method:', context.httpMethod) } 进入microservice http端点蓝图的AWS示例代码,如

在AWS Lambda代码中,如何获取HTTP方法,例如get、POST。。。来自AWS网关API的HTTP请求的安全性

我从上下文中了解到。httpMethod就是解决这个问题的方法

然而,我无法使它工作

例如,当我尝试添加以下3行时:

    if (context.httpMethod) {
            console.log('HTTP method:', context.httpMethod)
    }
进入microservice http端点蓝图的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,转到Integration Request部分,单击Mapping Templates,并为application/json添加一个新的映射模板。然后,选择application/json并选择Mapping Template,然后在编辑框中输入如下内容:

{
    "http_method": "$context.httpMethod"
}

然后,当您的Lambda函数被调用时,您应该会在传入的名为http_method的事件中看到一个新属性,该属性包含用于调用该函数的http方法。

API网关现在有一个内置的映射模板,可以传递诸如http方法、路由等内容。我不能嵌入,因为我没有足够的分数,但你明白了

以下是如何将其添加到API网关控制台的屏幕截图:


要到达那里,请导航到AWS控制台>API网关>选择资源,IE-GET/home>Integration Request>Mapping Templates>然后单击application/json并从上面的屏幕截图中显示的下拉列表中选择Method Request Passthrough

当我从函数创建一个模板microservice http端点python项目时,我遇到了这个问题。 因为它创建了一个HTTP API网关,而且只有REST API有,所以我无法完成这项工作。只更改Lambda的代码

基本上,代码也是这样做的,但我没有使用事件['httpMethod']

请检查以下内容:

import boto3
import json

print('Loading function')
dynamo = boto3.client('dynamodb')


def respond(err, res=None):
    return {
        'statusCode': '400' if err else '200',
        'body': err.message if err else json.dumps(res),
        'headers': {
            'Content-Type': 'application/json',
        },
    }


def lambda_handler(event, context):
    '''Demonstrates a simple HTTP endpoint using API Gateway. You have full
    access to the request and response payload, including headers and
    status code.

    To scan a DynamoDB table, make a GET request with the TableName as a
    query string parameter. To put, update, or delete an item, make a POST,
    PUT, or DELETE request respectively, passing in the payload to the
    DynamoDB API as a JSON body.
    '''
    print("Received event: " + json.dumps(event, indent=2))

    operations = {
        'DELETE': lambda dynamo, x: dynamo.delete_item(**x),
        'GET': lambda dynamo, x: dynamo.scan(**x),
        'POST': lambda dynamo, x: dynamo.put_item(**x),
        'PUT': lambda dynamo, x: dynamo.update_item(**x),
    }
    
    operation =  event['requestContext']['http']['method']

    if operation in operations:
        payload = event['queryStringParameters'] if operation == 'GET' else json.loads(event['body'])
        return respond(None, operations[operation](dynamo, payload))
    else:
        return respond(ValueError('Unsupported method "{}"'.format(operation)))
我将代码更改为:

操作=事件['httpMethod']

操作=事件['requestContext']['http']['method']

如何获得此解决方案


我只是返回了整个事件,检查了JSON并使用正确的格式进行处理。

谢谢。顺便说一句,您的答案中有一个小的输入错误:$context.httpMethod是$context.httpMethod,这对使用Chrome扩展高级REST客户端的人有用吗?当我使用它时,上下文变量的值为null,但它可以与Postman和DHC扩展一起使用,如果它是get端点,则可以在浏览器中直接调用。请确保在进行这些更改后重新部署端点。我花了很长时间才弄明白。文本是可搜索的,图像不是。Windows错误屏幕也不可复制复制,但将消息作为文本有助于找到要搜索的内容。列出人们认为在粘贴文本的文本而不是文本本身时值得投票否决的原因。这里的要点不是显示代码,而是向用户显示AWS API网关控制台中的面板是什么样子。这是更好的答案。即使被接受的答案是正确的,它也会替换信息,而不是添加/注释,这更可能是问题的意图,谢谢。对于那些使用Node.js运行时的用户,可以类似地执行:let operation=event.requestContext.http.method;