了解Alexa Skill- JavaScript内部的HTTP函数

问题描述 投票:0回答:1

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

函数httpGet(){返回新的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个回答
0
投票

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

const request = https.request(options, (response) => {
  // Here response 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();
© www.soinside.com 2019 - 2024. All rights reserved.