1

I am tying to call the external API from the lambda function for LEX bot intent and not able to communicate with external API, these APIs are hosted somewhere else. Same JS code is working from my local system, but not able to communicate from lambda function. so it is not an issue with the service, more like an issue in the AWS cloud network or something related. i looked at the cloud watch logs, but no errors are reported

I am not using VPC's my function is outside of VPC. any help would greatly appreciated

exports.handler = async (event) => {
console.log ("executing222222") ;
var https = require('https');

var options = {
  'method': 'POST',
  'hostname': 'ccc.com',
  'path': '/xxx',
  'headers': {
    'Authorization': 'bearer6ad1a3ae-2a1d-48e0-bf68-8669c5b9af62'
  }
};

console.log ("test"); 
var req = https.request(options, function (res) {
  console.log ("test1111"); 
  res.setEncoding('utf8');
  var returnData = "";
  res.on('data', function (chunk) {
    returnData += chunk;
  });
  console.log ("test11"); 
  res.on("end", function () {
    var body = JSON.parse(returnData) ;
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});

req.end();
};
Pras
  • 41
  • 1
  • 6
  • 1
    This looks like an async issue similar to this question: https://stackoverflow.com/questions/28449363/why-is-this-http-request-not-working-on-aws-lambda You are calling req.end() outside of the https call, so it is closing before the function returns. – Dylan May 06 '19 at 15:09
  • but the request statement itself is not executing.. var req = https.request(options, function (res) { . as i am not seeing the log statements added inside the function – Pras May 06 '19 at 19:21
  • I expect it is being triggered, but then req.end() is being called before the request returns a response. This is an async function, so the function calls https.request() and then calls req.end() without waiting for the callback from the request. – Dylan May 06 '19 at 21:56
  • How could I resolve then I tried commenting the req.end method it didn’t resolve issue, also tried with aws sdk and no luck their as well – Pras May 06 '19 at 23:17

1 Answers1

3

this code helps to resolve the async issue.

const http = require('http');

exports.handler = async (event, context) => {

    return new Promise((resolve, reject) => {
        const options = {
            host: 'ec2-18-191-89-162.us-east-2.compute.amazonaws.com',
            path: '/api/repos/r1639420d605/index?delta=true&clear=false',
            port: 8000,
            method: 'PUT'
        };

        const req = http.request(options, (res) => {
          resolve('Success');
        });

        req.on('error', (e) => {
          reject(e.message);
        });

        // send the request
        req.write('');
        req.end();
    });
};`enter code here`
Pras
  • 41
  • 1
  • 6