【问题标题】:How to get Lambda Function to get httpmethod from ApiGateway with method ANY?如何使用 ANY 方法获取 Lambda 函数以从 ApiGateway 获取 httpmethod?
【发布时间】:2019-08-09 01:57:05
【问题描述】:

我正在尝试创建一个 API 网关,它将采用 AWS 中的任何方法。一旦调用了 API,lambda 函数就会解析出发送的消息,并决定从那里做什么。所以,给定一个 API Gateway 方法:

Type: AWS::ApiGateway::Method
    Properties:
      RestApiId: !Ref myRestApi
      ResourceId: !Ref myResource
      HttpMethod: ANY
      AuthorizationType: NONE
      Integration:
        Type: AWS_PROXY
        IntegrationHttpMethod: POST
        Uri:
          Fn::Join:
          - ''
          - - 'arn:aws:apigateway:'
            - Ref: AWS::Region
            - :lambda:path/2015-04-30/functions/
            - Fn::GetAtt:
              - myLambdaFunction
              - Arn
            - /invocations

它会成功调用myLambdaFunction,那么我如何在node get 中获取实际发送HttpMethod 的lambda 函数?

例如:

exports.handler = (event, context, callback) => {
    const response = {
        statusCode: 200,
        headers: {
            "x-custom-header" : "This exists for reasons."
        }

    };

// I know that event doesn't actually have any httpmethod, but I'm not sure what it does have, or how to use it.
    switch(event.httpmethod) {
      case "POST":
        console.log("POST!!!");
        create(event, context, callback);
        break;
      case "GET":
        console.log("GET!!!");
        read(event, context, callback);
        break;
      case "PUT":
        console.log("PUT!!!");
        update(event, context, callback);
        break;
    }

上面的 lambda 应该能够 console.log 它得到的任何方法,但我不确定应该用什么来代替我刚刚编造的 event.httpmethod

【问题讨论】:

    标签: node.js amazon-web-services aws-lambda aws-api-gateway


    【解决方案1】:

    您正在寻找event.httpMethod(注意大写M)属性。

    如果您不确定您的 Lambda 事件有哪些数据,您可以随时使用

    记录结果
    console.log(event);
    

    结果将显示在与 Lambda 函数关联的 CloudWatch 日志中。

    对于 API Gateway 和 Lambda 之间的代理集成,您可以在 AWS API Gateway developer guide 中找到有关这些事件的具体详细信息:

    {
        "resource": "Resource path",
        "path": "Path parameter",
        "httpMethod": "Incoming request's method name"
        "headers": {String containing incoming request headers}
        "multiValueHeaders": {List of strings containing incoming request headers}
        "queryStringParameters": {query string parameters }
        "multiValueQueryStringParameters": {List of query string parameters}
        "pathParameters":  {path parameters}
        "stageVariables": {Applicable stage variables}
        "requestContext": {Request context, including authorizer-returned key-value pairs}
        "body": "A JSON string of the request payload."
        "isBase64Encoded": "A boolean flag to indicate if the applicable request payload is Base64-encode"
    }
    

    或者在AWS Lambda Developer Guide

    {
      "path": "/test/hello",
      "headers": {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Accept-Encoding": "gzip, deflate, lzma, sdch, br",
        "Accept-Language": "en-US,en;q=0.8",
        "CloudFront-Forwarded-Proto": "https",
        "CloudFront-Is-Desktop-Viewer": "true",
        "CloudFront-Is-Mobile-Viewer": "false",
        "CloudFront-Is-SmartTV-Viewer": "false",
        "CloudFront-Is-Tablet-Viewer": "false",
        "CloudFront-Viewer-Country": "US",
        "Host": "wt6mne2s9k.execute-api.us-west-2.amazonaws.com",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
        "Via": "1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net (CloudFront)",
        "X-Amz-Cf-Id": "nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==",
        "X-Forwarded-For": "192.168.100.1, 192.168.1.1",
        "X-Forwarded-Port": "443",
        "X-Forwarded-Proto": "https"
      },
      "pathParameters": {
        "proxy": "hello"
      },
      "requestContext": {
        "accountId": "123456789012",
        "resourceId": "us4z18",
        "stage": "test",
        "requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
        "identity": {
          "cognitoIdentityPoolId": "",
          "accountId": "",
          "cognitoIdentityId": "",
          "caller": "",
          "apiKey": "",
          "sourceIp": "192.168.100.1",
          "cognitoAuthenticationType": "",
          "cognitoAuthenticationProvider": "",
          "userArn": "",
          "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
          "user": ""
        },
        "resourcePath": "/{proxy+}",
        "httpMethod": "GET",
        "apiId": "wt6mne2s9k"
      },
      "resource": "/{proxy+}",
      "httpMethod": "GET",
      "queryStringParameters": {
        "name": "me"
      },
      "stageVariables": {
        "stageVarName": "stageVarValue"
      }
    }
    

    【讨论】:

      【解决方案2】:

      事件变量是您的 lambda 获取的给定 json 的请求。

      要使您的代码正常工作,您需要将以下 json 传递给 lambda

      { 
          httpmethod : "value"
      }
      

      其中的值将是 POST、GET 或 PUT。

      如果您转到按钮操作右侧的控制台,您可以使用事件 json 输入创建测试。

      【讨论】:

        【解决方案3】:

        我使用这个找到了httpMethod 值 -

        if (event.requestContext.http.method === 'GET') {
            // code goes here...
        }
        

        【讨论】:

          【解决方案4】:

          下面的代码可以用来查找方法。

          if (event.httpMethod === "GET") {
            // Get method code goes here
          } else if(event.httpMethod === "POST") {
            // Post method code goes here
          }
          

          示例event.json API Gateway 代理事件(REST API)

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-07-26
            • 1970-01-01
            • 2021-09-20
            • 2022-11-20
            • 1970-01-01
            • 2020-03-21
            • 1970-01-01
            相关资源
            最近更新 更多