Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send POST Request via AWS Lambda in Node.js

I want to send a POST Request to Twilio when an Intent is called from my Alexa Skill. When testing the Code, there are no errors, but the Request doesn't seem to go through. Testing the POST Request in Postman works.

function postToTwilio() {

var http = require("https");
var postData = JSON.stringify({
      'To' : '1234567',
      'From': '1234546',
      'Url': 'https://handler.twilio.com/twiml/blablabla',


  });

var options = {
  "method": "POST",
  "hostname": "https://api.twilio.com",
  "path": "/12344/Accounts/blablablablba/Calls.json",
  "headers": {
    "Authorization": "Basic blblablablablabla",
    "Content-Type": "application/x-www-form-urlencoded",
  }
};

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.write(postData);
req.end();

}
like image 508
NL97 Avatar asked Sep 14 '25 13:09

NL97


1 Answers

First of all, a request is a async call so you need to make alexa wait for the response.

To do that, you need to use async await process and using promises.

var postData = JSON.stringify({
      'To' : '1234567',
      'From': '1234546',
      'Url': 'https://handler.twilio.com/twiml/blablabla',


  });

var options = {
  "method": "POST",
  "hostname": "https://api.twilio.com",
  "path": "/12344/Accounts/blablablablba/Calls.json",
  "headers": {
    "Authorization": "Basic blblablablablabla",
    "Content-Type": "application/x-www-form-urlencoded",
  }
};

function get(options) {
  return new Promise(((resolve, reject) => {
    const request = https.request(options, (response) => {
      response.setEncoding('utf8');
      let returnData = '';

      if (response.statusCode < 200 || response.statusCode >= 300) {
        return reject(new Error(`${response.statusCode}: ${response.req.getHeader('host')} ${response.req.path}`));
      }

      response.on('data', (chunk) => {
        returnData += chunk;
      });

      response.on('end', () => {
        resolve(JSON.parse(returnData));
      });

      response.on('error', (error) => {
        reject(error);
      });
    });
    request.write(postData)
    request.end();
  }));
}

Then, when you call this get function:

let response = await get(options)

I haven't tested as a whole but that is the base skeleton.

Let me know if that works.

like image 121
Alex Avatar answered Sep 16 '25 16:09

Alex