【问题标题】:How do I send API request in APIGatewayProxyRequestEvent format? - AWS API Gateway Lambda Proxy如何以 APIGatewayProxyRequestEvent 格式发送 API 请求? - AWS API 网关 Lambda 代理
【发布时间】:2021-05-04 02:56:26
【问题描述】:

我有一个启用了 Lambda 代理集成的 POST API 设置。我的 Lambda 函数在这里是用 Java 编写的:

 public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
         
          //log some stuff
          Gson gson = new GsonBuilder().setPrettyPrinting().create();
          LambdaLogger logger = context.getLogger();
          logger.log("Method Start " +input );
          logger.log("CONTEXT: " + gson.toJson(context));
          
          //Initialize response and DB
          logger.log("Inizialize response and DB " );
          APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();
          dynamoDb = new DynamoDB(client);
          
          try {
              logger.log("Getting REST method type " );
              String restMethod = input.getHttpMethod();
              logger.log("REST method type " +restMethod);
              logger.log("Input body: "+input.getBody());
              
              if (restMethod.equals("POST")) {
                  logger.log("POST method Start " );
                  String requestString = input.getBody();
                  JSONParser parser = new JSONParser();
                  JSONObject requestJsonObject = (JSONObject) parser.parse(requestString);
                  String name = requestJsonObject.get("name").toString();
                  logger.log("Before DB call " );
                  sendDataToDb(name, response);
                  logger.log("POST code End " );
              }
              if (restMethod.equals("GET")) {
                 logger.log("GET method Start " );
                 Map<String,String>pathParameters = input.getPathParameters();
                 String name2 = pathParameters.get("name");
                 getDataFromDb(name2, response);
              }
              
          } catch(Exception e){
              response.setStatusCode(405);
              response.setBody("exception Thrown");
              logger.log("Exception: " +e);
          }

          return response;
      }

我可以通过 AWS Lambda 和 API Gateway 控制台发送 POST API 请求,并且运行良好。我得到了完美的回应和 API/Lambda 函数。但是每当我尝试通过 curl 或 postman 或 javascript 提取发送相同的 POST API 时,我的 Lambda 都会收到 null 作为 APIGatewayProxyRequestEvent。

这是我正在测试的示例 javascript:

    <script>
        // define the callAPI function that takes a first name and last name as parameters
        var callPostAPI = (name)=>{
            // instantiate a headers object
            var myHeaders = new Headers();
            // add content type header to object
            myHeaders.append("Content-Type", "application/json");
            // using built in JSON utility package turn object to string and store in a variable
            var raw = JSON.stringify({"name":name});
            // create a JSON object with parameters for API call and store in a variable
            var requestOptions = {
                resource: '/',
                path:'/',
                httpMethod: 'POST',
                headers: myHeaders,
                multiValueHeaders: 'X-Forwarded-Proto=[https]',
                queryStringParameters: '{}',
                multiValueQueryStringParameters: '{}',
                pathParameters: '{proxy=}',
                stageVariables: '{baz=qux}',
                requestContext: '{accountId: 123456789012,resourceId: 123456,stage: prod,requestId: c6af9ac6-7b61-11e6-9a41-93e8deadbeef,identity: {sourceIp: 127.0.0.1,userAgent: Custom User Agent String,},resourcePath: /{proxy+},httpMethod: POST,apiId: 1234567890,path: /prod/path/to/resource,}',
                body: raw,
                isBase64Encoded: false,
                method: 'POST',
                redirect: 'follow'
            };
            // make API call with parameters and use promises to get response
            fetch("https://t3fl0anfw2.execute-api.us-east-1.amazonaws.com/dev", requestOptions)
            .then(response => response.text())
            .then(result => alert(JSON.parse(result).body))
            .catch(error => console.log('error', error));
        }
        
    </script>

所以我知道它可以通过 AWS 控制台工作,但我无法从这些控制台之外的任何设备上工作。我应该以特定的格式发送这些 API 请求吗?我尝试复制 Lambda/APIGateway 控制台发送的相同格式,但没有成功。我似乎找不到有关此特定用例的任何文档,因此感谢您提供任何帮助。

【问题讨论】:

  • 在尝试从 Javascript 调用时是否遇到任何 CORS 错误?
  • 是的,我看到访问 **** 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

标签: amazon-web-services aws-lambda aws-api-gateway


【解决方案1】:

所以您可能会遇到 CORS 问题。

您需要在 API Gateway 中启用 CORS,然后您还需要在 API Gateway 响应的响应中包含 CORS 标头。 (在实际响应中包含它通常会被忽略,因此请确保这样做

response = {
        statusCode: 200,
        **headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "https://www.example.com",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        },**
        body: JSON.stringify('Example'),
    };
    return response;
};

https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-28
    • 2020-02-24
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 2021-11-06
    相关资源
    最近更新 更多