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



我正在尝试创建一个 AWS Lambda 函数,该函数将按计划调用 DELETE。

我正在使用 Node.js。仅从 Node 运行时.js在我的本地计算机上,请求工作正常。

这是代码:

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(); 

我的输出是这样的:

Do the DELETE call
DELETE result:
{"message":"Cleanup triggered"}
Call completed

正如我所料。但是,当我从 AWS Lambda 函数内部运行时,我得到null的结果,Lambda 函数的日志输出是这样的。

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

请注意,它打印出"执行 DELETE 调用",所以我知道它正在进入我的代码,但没有打印出任何其他内容。

Lambda 的主体是这样的:

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

为什么我的 API 调用在我的本地计算机上工作时不从 Lambda 函数执行?

您正在使用异步 Lambda 函数处理程序,但未等待 HTTP 请求。这会导致函数在https.request()调用完成之前完成执行。

如果要使用回调而不是 promise,请为函数定义一个非异步处理程序:

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

最新更新