简体   繁体   English

AWS Lambda 与 API 网关和 Node.js 返回 HTTP 50

[英]AWS Lambda with API gateway and Node.js returning HTTP 502

Im testing functionality between AWS Lambda and API gateway.我正在测试 AWS Lambda 和 API 网关之间的功能。 My lambda function is using a Node and I have defined the parameters that i want to be pulling from S3.我的 lambda function 正在使用节点,我已经定义了我想从 S3 中提取的参数。 This is my lambda:这是我的 lambda:

console.log('Loading function');
const aws = require('aws-sdk');
const s3 = new aws.S3({ apiVersion: '2006-03-01' });

exports.handler = async (event, context) => {
    const bucket = event.Records[0].s3.bucket.name;
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
    const params = {
        Bucket: 'testing-api-lambda-s3-jfr',
        Key: 'sample-file-testing.csv',
    };
    
    exports.sendRes = (body, status = 200) => {
    const response = {
        statusCode: status,
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(body)
    };
    return response;
};

The test event on lambda returns OK, so i think lambda its fine: lambda 上的测试事件返回 OK,所以我认为 lambda 很好:

Test Event Name
test

Response
"text/csv"

Function Logs
START RequestId: 07d8ea41-976b-4e49-9fb7-ccfafca15dcf Version: $LATEST
2022-02-03T19:38:46.871Z    07d8ea41-976b-4e49-9fb7-ccfafca15dcf    INFO    CONTENT TYPE: text/csv
END RequestId: 07d8ea41-976b-4e49-9fb7-ccfafca15dcf
REPORT RequestId: 07d8ea41-976b-4e49-9fb7-ccfafca15dcf  Duration: 499.10 ms Billed Duration: 500 ms Memory Size: 128 MB Max Memory Used: 80 MB

Request ID
07d8ea41-976b-4e49-9fb7-ccfafca15dcf

On my API gateway, i have it configured as GET with no query strings or path parameters defined:在我的 API 网关上,我将其配置为 GET,没有定义查询字符串或路径参数: 在此处输入图像描述

And on the test the error is:在测试中,错误是:

{
  "message": "Internal server error"
}

在此处输入图像描述

Full API gateway execution logs:完整的 API 网关执行日志:

Execution log for request 2866b8b2-bd57-49f7-aad9-1a9279612364
Thu Feb 03 19:44:42 UTC 2022 : Starting execution for request: 2866b8b2-bd57-49f7-aad9-1a9279612364
Thu Feb 03 19:44:42 UTC 2022 : HTTP Method: GET, Resource Path: /
Thu Feb 03 19:44:42 UTC 2022 : Method request path: {}
Thu Feb 03 19:44:42 UTC 2022 : Method request query string: {}
Thu Feb 03 19:44:42 UTC 2022 : Method request headers: {}
Thu Feb 03 19:44:42 UTC 2022 : Method request body before transformations: 
Thu Feb 03 19:44:42 UTC 2022 : Endpoint request URI: https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-1:143578772304:function:getObjectNode/invocations
Thu Feb 03 19:44:42 UTC 2022 : Endpoint request headers: {X-Amz-Date=20220203T194442Z, x-amzn-apigateway-api-id=vzcwgufch1, Accept=application/json, User-Agent=AmazonAPIGateway_vzcwgufch1, Host=lambda.us-east-1.amazonaws.com, X-Amz-Content-Sha256=ec78e1a3cab036558869aced97bcd18b2213fcab99c7a38ddc15d6bf509a5f5b, X-Amzn-Trace-Id=Root=1-61fc30aa-f6d4b97e6327eed29d022b45, x-amzn-lambda-integration-tag=2866b8b2-bd57-49f7-aad9-1a9279612364, Authorization=*********************************************************************************************************************************************************************************************************************************************************************************************************************************************a0c1a3, X-Amz-Source-Arn=arn:aws:execute-api:us-east-1:143578772304:vzcwgufch1/test-invoke-stage/GET/, X-Amz-Security-Token=IQoJb3JpZ2luX2VjEEQaCXVzLWVhc3QtMSJIMEYCIQDE4SYIymD/u99+1dzLRSk8U+DbUxCC9ygNy6aYr1SjhQIhAN9P2Oh/UyQl1L0mLSNTGhNRFGz2G5irLwGI7gHbs/4eKvoDCHwQABoMM [TRUNCATED]
Thu Feb 03 19:44:42 UTC 2022 : Endpoint request body after transformations: {"resource":"/","path":"/","httpMethod":"GET","headers":null,"multiValueHeaders":null,"queryStringParameters":null,"multiValueQueryStringParameters":null,"pathParameters":null,"stageVariables":null,"requestContext":{"resourceId":"dw7k4w6igh","resourcePath":"/","httpMethod":"GET","extendedRequestId":"M-yKsEC5IAMFegA=","requestTime":"03/Feb/2022:19:44:42 +0000","path":"/","accountId":"143578772304","protocol":"HTTP/1.1","stage":"test-invoke-stage","domainPrefix":"testPrefix","requestTimeEpoch":1643917482625,"requestId":"2866b8b2-bd57-49f7-aad9-1a9279612364","identity":{"cognitoIdentityPoolId":null,"cognitoIdentityId":null,"apiKey":"test-invoke-api-key","principalOrgId":null,"cognitoAuthenticationType":null,"userArn":"arn:aws:iam::143578772304:user/fernando","apiKeyId":"test-invoke-api-key-id","userAgent":"aws-internal/3 aws-sdk-java/1.12.138 Linux/5.4.156-94.273.amzn2int.x86_64 OpenJDK_64-Bit_Server_VM/25.312-b07 java/1.8.0_312 vendor/Oracle_Corporation cfg/retry-mod [TRUNCATED]
Thu Feb 03 19:44:42 UTC 2022 : Sending request to https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-east-1:143578772304:function:getObjectNode/invocations
Thu Feb 03 19:44:42 UTC 2022 : Received response. Status: 200, Integration latency: 24 ms
Thu Feb 03 19:44:42 UTC 2022 : Endpoint response headers: {Date=Thu, 03 Feb 2022 19:44:42 GMT, Content-Type=application/json, Content-Length=261, Connection=keep-alive, x-amzn-RequestId=62424064-5199-48b7-ad4e-f8976d86e514, X-Amz-Function-Error=Unhandled, x-amzn-Remapped-Content-Length=0, X-Amz-Executed-Version=$LATEST, X-Amzn-Trace-Id=root=1-61fc30aa-f6d4b97e6327eed29d022b45;sampled=0}
Thu Feb 03 19:44:42 UTC 2022 : Endpoint response body before transformations: {"errorType":"TypeError","errorMessage":"Cannot read property '0' of undefined","trace":["TypeError: Cannot read property '0' of undefined","    at Runtime.exports.handler (/var/task/index.js:12:33)","    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"]}
Thu Feb 03 19:44:42 UTC 2022 : Lambda execution failed with status 200 due to customer function error: Cannot read property '0' of undefined. Lambda request id: 62424064-5199-48b7-ad4e-f8976d86e514
Thu Feb 03 19:44:42 UTC 2022 : Method completed with status: 502

Any suggestions?有什么建议么? thank you谢谢你

The error message from the execution logs says that the event object does not have an array Records with some bucket information.执行日志中的错误消息表明event object 没有包含一些存储桶信息的数组Records The reason for this is that API Gateway request events do not have this array.原因是API网关请求事件没有这个数组。 API Gateway does not anything about your buckets as long as you do not pass the bucket information in a REST request body.只要您不在 REST 请求正文中传递存储桶信息,API 网关就不会与您的存储桶有关。

Moreover, you are expecting a bucket name and key from the API gateway request using these lines:此外,您期望使用以下行从 API 网关请求中获得存储桶名称和密钥:

const bucket = event.Records[0].s3.bucket.name;
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));

But you never really use these variables anywhere, essentially hardcoding your own bucket name and key with these lines:但是你从来没有在任何地方真正使用过这些变量,本质上是用这些行硬编码你自己的存储桶名称和密钥:

const params = {
    Bucket: 'testing-api-lambda-s3-jfr',
    Key: 'sample-file-testing.csv',
};

Just simply remove these two lines from your code, if you don't need them.如果不需要,只需从代码中删除这两行即可。

const bucket = event.Records[0].s3.bucket.name;
const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));

I feel like you are confusing how the event object should look like when your Lambda is triggered by an S3 event, compared to what it would look like if the Lambda would be triggered by API Gateway proxy integration. I feel like you are confusing how the event object should look like when your Lambda is triggered by an S3 event, compared to what it would look like if the Lambda would be triggered by API Gateway proxy integration. If you want to know the how the event object is structured when the API Gateway invokes it, you may want to check out this page from the AWS docs.如果您想知道当 API 网关调用event object 时它是如何构造的,您可能需要查看 AWS 文档中的此页面

As per the execution logs your API Gateway is not able to transform response received from lambda.根据执行日志,您的 API 网关无法转换从 lambda 收到的响应。

You need to provide your API a model defining response structure such that it can transform responses.您需要为您的 API 提供一个 model 定义响应结构,以便它可以转换响应。 This falls under Mapping templates.这属于映射模板。

https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-gateway-response-using-the-console.html https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-gateway-response-using-the-console.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AWS API 网关与 Lambda HTTP GET 请求(Node.js)502 错误网关 - AWS API Gateway with Lambda HTTP GET Request (Node.js) 502 Bad Gateway 节点 JS AWS 无服务器 502 HTTP/1.1 502 错误网关 - Node JS AWS Serverless 502 HTTP/1.1 502 Bad Gateway 如何使用Javascript(Node.js)读取通过Http Post发送的变量值并在AWS API Gateway Lambda上获取? - How to read variable value sent over Http Post and Get on AWS API Gateway Lambda using Javascript(Node.js)? 使用 node.js 从 AWS Lambda 将自定义错误传回 AWS API Gateway - Passing custom errors back to AWS API Gateway from AWS Lambda using node.js AWS Lambda/API 网关 - 传递 ID 以使用 node.js 在 mysql 中删除一行 - AWS Lambda/API Gateway - Pass an ID to delete a row in mysql with node.js AWS + API网关+ Lambda + Node.js在Google上的操作ApiAiApp - AWS + API Gateway + Lambda + Node.js actions-on-google ApiAiApp 将Node.js API与AWS Lambda混合 - Mixing Node.js API with AWS Lambda 在 AWS Lambda for Node 模板中返回没有 API 网关的 HTML 响应 - Returning HTML response without API gateway in AWS Lambda for Node template AWS http api 网关 + lambda (node/express) 内部服务器错误 - AWS http api gateway + lambda (node/express) Internal Server Error 如何从AWS Lambda Node.js 8.10异步函数向AWS API网关返回net.socket数据? - How to return net.socket data from AWS Lambda Node.js 8.10 async function to AWS API gateway?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM