有没有办法从aws lamda函数(node js)调用Rest API

时间:2019-05-06 12:59:31

标签: node.js aws-lambda aws-lex

我想从lambda函数中为LEX bot意图调用外部API,并且无法与外部API通信,这些API托管在其他地方。相同的JS代码正在我的本地系统上运行,但无法通过lambda函数进行通信。因此它与服务无关,更像是AWS云网络中的问题或其他相关问题。我查看了云监视日志,但未报告任何错误

我没有使用VPC,我的功能不在VPC之外。任何帮助将不胜感激

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

1 个答案:

答案 0 :(得分:0)

此代码有助于解决异步问题。

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`