【问题标题】:Send POST Request via AWS Lambda in Node.js在 Node.js 中通过 AWS Lambda 发送 POST 请求
【发布时间】:2019-05-30 07:40:21
【问题描述】:

当从我的 Alexa Skill 调用 Intent 时,我想向 Twilio 发送 POST 请求。测试代码时,没有错误,但请求似乎没有通过。在 Postman 中测试 POST 请求有效。

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

}

【问题讨论】:

  • 您在req 上没有错误处理程序,请尝试在其中添加一个,然后查看是否报告了任何错误。正如所写的那样,它们可能只是没有被处理。请参阅the docs 了解更多信息。
  • 我认为你的Lambda函数在post请求完成之前已经完成,显示你在哪里使用postToTwilio 函数,并调用回调函数。

标签: node.js aws-lambda alexa


【解决方案1】:

首先,请求是异步调用,所以你需要让alexa等待响应。

为此,您需要使用异步等待过程并使用承诺。

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

那么,当你调用这个get函数时:

let response = await get(options)

我没有整体测试过,但这是基本骨架。

让我知道这是否有效。

【讨论】:

  • 您好,谢谢您的回复!我复制了你所做的一切。只有一个问题,当调用 get 函数时(让 response = await api.get(options) 我应该输入什么而不是“api”?我收到消息:“unexpected token api”
  • 抱歉,刚刚调用了 get(...)。我通常在外部类中有这个调用,所以我总是把它称为 api.whatever 更新了答案
猜你喜欢
  • 2018-05-04
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 2017-05-03
相关资源
最近更新 更多