James
James

Reputation: 553

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.

I'm using Node.js. When running just from Node.js on my local machine the request works fine.

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:

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.

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.

The body of the Lambda is like this:

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?

Upvotes: 1

Views: 1766

Answers (1)

Paradigm
Paradigm

Reputation: 2026

You are using an async Lambda function handler, but the HTTP request is not awaited. This causes the function to finish execution before the https.request() call can complete.

If you would like to use callbacks and not promises, then define a non-async handler for the function:

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

Upvotes: 2

Related Questions