Search code examples
node.jshttpsaws-lambdanodes

AWS Lambda function using HTTP module not making any request


I have a AWS Lambda function using Node.js 12.x. Here is my code:

exports.handler =  async function(event, context) {
const https = require('https');

const sheetId = 01234;

const testData = JSON.stringify({"toTop":true, "cells": [ {"columnId": 3148210723153796, "value": 'TEST'} ] });

const options = {
    hostname: 'api.website.com',
    port: 443,
    path: `/logs`,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer oefohjeoiefoijn'
    }
};

const req = https.request(options, (res) => {
    console.log(`STATUS: ${res.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
    });
    res.on('end', () => {
        console.log('No more data in response.');
    });
});

req.on('error', (e) => {
    console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(testData);
req.end();
}

The request is not being executed. I am not receiving any errors in Cloudwatch. The exact code (with the Handler export removed) is working fine in Node.js 12.x on my machine.


Solution

  • Your lambda function terminates before the response is received because you're not waiting for the callback to return.

    You can wrap your request into a promise:

    exports.handler = async function(event, context) {
    
        return new Promise((resolve, reject) => {
    
            const req = https.request(options, (res) => {
              // ...
              resolve();
            });
    
            req.on('error', (e) => {
                reject();
            });
    
            req.write(testData);
            req.end();
        });
    }