node.jsaws-lambdaaws-lex

Is there a way to call the Rest API from the aws lamda functions ( node js)


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

Solution

  • 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`