简体   繁体   English

Node.js HTTPS 调用在 AWS Lambda 中不起作用

[英]Node.js HTTPS call not working in AWS Lambda

I'm trying to create an AWS Lambda function that will call a DELETE on a schedule.我正在尝试创建一个 AWS Lambda function ,它将按计划调用 DELETE。

I'm using Node.js.我正在使用 Node.js。 When running just from Node.js on my local machine the request works fine.在我的本地计算机上仅从 Node.js 运行时,请求工作正常。

Here is the code:这是代码:

const https = require('https');

var options = {
    host: 'MY_HOST',
    path: '/v1/api/orders',
    port: 80,
    method: 'DELETE'
};

console.info('Do the DELETE call');

var reqDelete = https.request(options, function(res) {

    res.on('data', function(d) {
        console.info('DELETE result:\n');
        console.log(d.toString('utf8'));
        console.info('\nCall completed');
    });

});

 reqDelete.on('error', function(e) {
    console.error(e);
});


reqDelete.end(); 

My output is like this:我的 output 是这样的:

Do the DELETE call
DELETE result:

{"message":"Cleanup triggered"}

Call completed

Just as I expect.正如我所料。 However when I run from inside an AWS Lambda function I get the result of null and the Log output for the Lambda function is this. However when I run from inside an AWS Lambda function I get the result of null and the Log output for the Lambda function is this.

START RequestId: fb2a1969-94e8-4c11-b43e-14ff6a4cc426 Version: $LATEST
2020-06-16T01:42:06.875Z    fb2a1969-94e8-4c11-b43e-14ff6a4cc426    INFO    Do the DELETE call
END RequestId: fb2a1969-94e8-4c11-b43e-14ff6a4cc426
REPORT RequestId: fb2a1969-94e8-4c11-b43e-14ff6a4cc426  Duration: 483.49 ms Billed Duration: 500 ms  
Memory Size: 128 MB Max Memory Used: 67 MB  Init Duration: 125.35 ms

Notice that it prints out the "Do the DELETE call" so I know it's getting to my code but nothing else is being printed out.请注意,它会打印出“执行 DELETE 调用”,因此我知道它正在访问我的代码,但没有打印出其他任何内容。

The body of the Lambda is like this: Lambda的主体是这样的:

exports.handler = async (event) => {
    // The exact code from above with the actual host name.
};

Why is my API call not executed from the Lambda function when it is working from my local machine?为什么我的 API 调用没有从 Lambda function 在我的本地计算机上执行?

You are using an async Lambda function handler , but the HTTP request is not awaited.您正在使用异步 Lambda function 处理程序,但不等待 HTTP 请求。 This causes the function to finish execution before the https.request() call can complete.这会导致 function 在https.request()调用完成之前完成执行。

If you would like to use callbacks and not promises, then define a non-async handler for the function:如果您想使用回调而不是承诺,则为 function 定义一个非异步处理程序:

exports.handler = (event) => {
    // The exact code from above with the actual host name.
};

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM