【问题标题】:Error with Lambda via AWS API Gateway using proxy使用代理通过 AWS API Gateway 的 Lambda 错误
【发布时间】:2021-09-19 15:40:58
【问题描述】:

我目前在使用 lambda 函数和 API 网关时遇到问题。 我在 API Gateway 中启用了代理集成,以便返回来自 Lambda 函数的状态代码。 现在我的问题是根本没有执行调用。 Error Picture

如果我测试 Lambda,一切正常,并且数据库中的条目被执行。不通过 API 网关。

我的问题是什么?

非常感谢您的帮助!

Test

    const mysql = require('mysql');
var cors = require('cors');
const express = require('express');

const app = express();
app.use(cors());
const connection = mysql.createConnection({

    //following param coming from aws lambda env variable 

    host: process.env.RDS_HOSTNAME,

    user: process.env.RDS_USERNAME,

    password: process.env.RDS_PASSWORD,

    port: process.env.RDS_PORT,

    // calling direct inside code  

    connectionLimit: 10,

    multipleStatements: true,
    // Prevent nested sql statements 
    connectionLimit: 1000,
    connectTimeout: 60 * 60 * 1000,
    acquireTimeout: 60 * 60 * 1000,
    timeout: 60 * 60 * 1000,
    debug: true
});
let query;
let addressId;
let personId;
exports.handler = async (event, context, callback) => {
    try{
        query="Insert into sys.Address (street, houseNumber, postalCode, city) Values ('"+event.street+"', "+event.houseNumber+", "+event.postalCode+", '"+event.city+"')";
        let dataAddress = await new Promise((resolve, reject) => {
                connection.query(query, function (err, result) {
                    if (err) {
                        console.log("Error->" + err);
                        reject(err);
                    }
                    resolve(result);
                });
        });
        
        addressId=dataAddress.insertId;
        console.log("addressId=" +addressId);
        query="Insert into sys.Persons (lastName, firstName, dateOfBirth, phoneNumber, addressId) Values ('"+event.lastName+"', '"+event.firstName+"', '"+event.dateOfBirth+"', "+event.phoneNumber+", "+addressId+")";
        let dataPerson = await new Promise((resolve, reject) => {
                connection.query(query, function (err, result) {
                    if (err) {
                        console.log("Error->" + err);
                        reject(err);
                    }
                    resolve(result);
                });
        });
    
        var response = {
        "statusCode": 201,
        "headers": {
            "my_header": "my_value"
        },
        "body": JSON.stringify(dataAddress, dataPerson),
        "isBase64Encoded": false
    };
    callback(null, response);
    } catch (err) {
        var response = {
        "statusCode": 400,
        "headers": {
            "my_header": "my_value"
        },
        "body": JSON.stringify(err.message),
        "isBase64Encoded": false
    };
        callback(null, response);
    } 
};

编辑:

我将此添加为 IAM 政策:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "execute-api:*"
            ],
            "Resource": [
                "arn:aws:execute-api:*:*:*"
            ]
        }
    ]
}

但还是会出现这个错误:

Request: /persons
Status: 400
Latency: 474 ms
Response Body
"ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'field list'"
Response Headers
{"my_header":"my_value","X-Amzn-Trace-Id":"Root=1-60e95617-157c462e040f133437c0add3;Sampled=0"}
Logs
Execution log for request 2ff23dad-8233-4785-944d-1c21c4d92862
Sat Jul 10 08:11:03 UTC 2021 : Starting execution for request: 2ff23dad-8233-4785-944d-1c21c4d92862
Sat Jul 10 08:11:03 UTC 2021 : HTTP Method: POST, Resource Path: /persons
Sat Jul 10 08:11:03 UTC 2021 : Method request path: {}
Sat Jul 10 08:11:03 UTC 2021 : Method request query string: {}
Sat Jul 10 08:11:03 UTC 2021 : Method request headers: {}
Sat Jul 10 08:11:03 UTC 2021 : Method request body before transformations: {
  "lastName": "Jan",
  "firstName": "Semrau",
  "street": "Musterstraße",
  "houseNumber": 3,
  "postalCode": 12345,
  "city": "Musterstadt",
  "dateOfBirth": "2021-04-03",
  "phoneNumber": 123456789
}
Sat Jul 10 08:11:03 UTC 2021 : Endpoint request URI: https://lambda.eu-central-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:eu-central-1:983309467882:function:postPerson/invocations
Sat Jul 10 08:11:03 UTC 2021 : Endpoint request headers: {x-amzn-lambda-integration-tag=2ff23dad-8233-4785-944d-1c21c4d92862, Authorization=***************************************************************************************************************************************************************************************************************************************************************************************************************************793b24, X-Amz-Date=20210710T081103Z, x-amzn-apigateway-api-id=jo9o1lyptc, X-Amz-Source-Arn=arn:aws:execute-api:eu-central-1:983309467882:jo9o1lyptc/test-invoke-stage/POST/persons, Accept=application/json, User-Agent=AmazonAPIGateway_jo9o1lyptc, X-Amz-Security-Token=IQoJb3JpZ2luX2VjELf//////////wEaDGV1LWNlbnRyYWwtMSJHMEUCIQCG1vvlhi8qDp+i7JtDFT7BNyEdYevsqonEe0z4jy2g3wIgQ1psCpqYgdQBomcXcUaufcpvVake3KzP2XXKsoH9oG8qiQQIoP//////////ARACGgw0NzQyNDAxNDY4MDIiDGNjM6AtNofwy1P8VyrdA+R4jETkW9/rFwjhU8a9dIsM6DlvJPjJ8ruBUtcl6m/VcYT+P+AkUrLNXwPR9OM2Ruj9RKWEPgfp3kEHyu/s0CDmgHmUmvxnP4eRDSOY1ruBpC4SHpdoDCXj933o1x [TRUNCATED]
Sat Jul 10 08:11:03 UTC 2021 : Endpoint request body after transformations: {"resource":"/persons","path":"/persons","httpMethod":"POST","headers":null,"multiValueHeaders":null,"queryStringParameters":null,"multiValueQueryStringParameters":null,"pathParameters":null,"stageVariables":null,"requestContext":{"resourceId":"488rd3","resourcePath":"/persons","httpMethod":"POST","extendedRequestId":"CPpjvER7FiAFS7Q=","requestTime":"10/Jul/2021:08:11:03 +0000","path":"/persons","accountId":"983309467882","protocol":"HTTP/1.1","stage":"test-invoke-stage","domainPrefix":"testPrefix","requestTimeEpoch":1625904663802,"requestId":"2ff23dad-8233-4785-944d-1c21c4d92862","identity":{"cognitoIdentityPoolId":null,"cognitoIdentityId":null,"apiKey":"test-invoke-api-key","principalOrgId":null,"cognitoAuthenticationType":null,"userArn":"arn:aws:iam::983309467882:root","apiKeyId":"test-invoke-api-key-id","userAgent":"aws-internal/3 aws-sdk-java/1.11.1030 Linux/5.4.116-64.217.amzn2int.x86_64 OpenJDK_64-Bit_Server_VM/25.292-b10 java/1.8.0_292 vendor/Oracle_Corpora [TRUNCATED]
Sat Jul 10 08:11:03 UTC 2021 : Sending request to https://lambda.eu-central-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:eu-central-1:983309467882:function:postPerson/invocations
Sat Jul 10 08:11:04 UTC 2021 : Received response. Status: 200, Integration latency: 469 ms
Sat Jul 10 08:11:04 UTC 2021 : Endpoint response headers: {Date=Sat, 10 Jul 2021 08:11:04 GMT, Content-Type=application/json, Content-Length=153, Connection=keep-alive, x-amzn-RequestId=26ba9976-89c5-4e0d-9ae6-f7340ab0c040, x-amzn-Remapped-Content-Length=0, X-Amz-Executed-Version=$LATEST, X-Amzn-Trace-Id=root=1-60e95617-157c462e040f133437c0add3;sampled=0}
Sat Jul 10 08:11:04 UTC 2021 : Endpoint response body before transformations: {"statusCode":400,"headers":{"my_header":"my_value"},"body":"\"ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'field list'\"","isBase64Encoded":false}
Sat Jul 10 08:11:04 UTC 2021 : Method response body after transformations: "ER_BAD_FIELD_ERROR: Unknown column 'undefined' in 'field list'"
Sat Jul 10 08:11:04 UTC 2021 : Method response headers: {my_header=my_value, X-Amzn-Trace-Id=Root=1-60e95617-157c462e040f133437c0add3;Sampled=0}
Sat Jul 10 08:11:04 UTC 2021 : Successfully completed execution
Sat Jul 10 08:11:04 UTC 2021 : Method completed with status: 400

【问题讨论】:

  • 你能提供执行的查询吗?
  • 我发布了 Lambda 代码
  • 您的错误屏幕截图似乎与查询或其格式有关。既然你说,它不是通过 API 网关调用,你是否授予权限并添加 API 网关调用 lambda 所需的资源策略?
  • 你有一个例子可以告诉我怎么做吗?

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


【解决方案1】:

检查您是否创建了具有适当权限的 IAM 策略。

例子:

API 网关的 IAM 角色

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "apigateway.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

IAM 调用 lambda 函数:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "lambda:InvokeFunction",
            "Resource": "*"
        }
    ]
}

参考:-https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html

以上方法足以让API网关调用你的Lambda了,如果还是不行,建议你试试this as last step

【讨论】:

  • 我是否必须将 IAM 添加到特定的网关/功能?
  • 是的,使用对应的arn。参考:-docs.amazonaws.cn/en_us/apigateway/latest/developerguide/…
  • 您是否将 IAM 分配给具有适当权限的 API 网关以调用 Lambda?如果它不起作用,您可以尝试我上面的答案中提到的“这是最后一步”
猜你喜欢
  • 1970-01-01
  • 2018-05-04
  • 2017-04-07
  • 2021-01-08
  • 2017-10-04
  • 1970-01-01
  • 2018-01-15
  • 2016-06-02
  • 1970-01-01
相关资源
最近更新 更多