【问题标题】:Understanding HTTP function inside Alexa Skill-- JavaScript了解 Alexa Skill 中的 HTTP 函数——JavaScript
【发布时间】:2020-05-19 20:00:45
【问题描述】:

我目前正在学习如何将我的 Amazon Lambda 函数(在 js 中)连接到 API。我发现以下代码有效,但我对 javascript 和 API 很陌生,并且不确定它在做什么。有人可以向我解释这个功能的作用以及它是如何工作的吗?谢谢!

function httpGet() {
  return new Promise(((resolve, reject) => {

    var options = {
      host: 'api.icndb.com',
      port: 443,
      path: '/jokes/random',
      method: 'GET',
    };

    const request = https.request(options, (response) => {
      response.setEncoding('utf8');
      let returnData = '';

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

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

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

【问题讨论】:

    标签: javascript api httprequest alexa alexa-skills-kit


    【解决方案1】:

    这里的response 对象是一个node.js stream,特别是一个“推送”流。 (This 文章很好地解释了推/拉流)。

    const request = https.request(options, (response) => {
      // Your request has been successfully made and you are 
      // handed a response object which is a stream, which will emit
      // a 'data' event when some data is available.
      response.setEncoding('utf8');
      let returnData = '';
    
      // A chunk of data has been pushed by the stream,
      // append it to the final response
      response.on('data', (chunk) => {
        returnData += chunk;
      });
    
      // All the data has been pushed by the stream.
      // 'returnData' has all the response data. Resolve the 
      // promise with the data.
      response.on('end', () => {
        resolve(JSON.parse(returnData));
      });
    
      // Stream has thrown an error.
      // Reject the promise
      response.on('error', (error) => {
        reject(error);
      });
    });
    request.end();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-15
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多