node.js - 在 lambda 函数中使用 https 调用和 Nodejs 返回数据

标签 node.js https aws-lambda

我正在尝试在 lambda 函数内设置 HTTPS 调用。我已经阅读了很多教程,但显然我还不够理解。

我只是使用 Chuck Norris 笑话 API 的基本示例。

// Load the AWS SDK for Node.js
let AWS = require('aws-sdk');
// Set the region 
AWS.config.update({region: 'us-east-2'});

const https = require('https');

let url = "https://api.chucknorris.io/jokes/random"

exports.handler = async (event, context, callback) => {


    function httpsCall() {
        
        return new Promise((resolve, reject) => {
            const options = {
                host: 'api.chucknorris.io',
                path: '/jokes/random',
                port: 443,
                method: 'GET'
            };
    
            const req = https.request(options, (res) => {
              resolve('Success');
            });
    
            req.on('error', (e) => {
              reject(e.message);
            });
    
            // send the request
            req.write('');
            req.end();
        });
    }
    
    console.log(await httpsCall())
    // httpsCall().then(resp => resp.json()).then(data => console.log(data))

};

我能得到的最好结果就是它返回“成功” 使用 .then() 链接不会产生任何结果,尝试使用 reslove 函数中的“res”返回也不会产生任何结果。

我不知道还能尝试什么......

有什么建议吗?

最佳答案

您可以使用 response.end 事件来解决 promise 。

// Load the AWS SDK for Node.js
let AWS = require('aws-sdk');
// Set the region 
AWS.config.update({ region: 'us-east-2' });

const https = require('https');

let url = "https://api.chucknorris.io/jokes/random"

exports.handler = async (event, context, callback) => {


  async function httpsCall() {

    return new Promise((resolve, reject) => {
      const options = {
        host: 'api.chucknorris.io',
        path: '/jokes/random',
        port: 443,
        method: 'GET'
      };

      const req = https.request(options, (res) => {

        var body = '';

        res.on('data', function (chunk) {
          body += chunk;
        })

        res.on('end', () => {
          resolve(JSON.parse(body));
        })
      });

      req.on('error', (e) => {
        reject(e.message);
      });

      // send the request
      req.write('');
      req.end();
    });
  }
  console.log(await httpsCall())
  // httpsCall().then(resp => resp.json()).then(data => console.log(data))
};

关于node.js - 在 lambda 函数中使用 https 调用和 Nodejs 返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59135458/

相关文章:

amazon-web-services - 我可以使用AWS lambda来压缩上传到S3的图像吗?

node.js - 如何允许 Telegram 机器人读取本地文件系统

node.js - Nodejs 监听全局热键按下

php - 如何在 PHP 中检测站点是否支持 HTTP/2

python - 如何关闭requests.Session()?

apache - htaccess https 到 http 重定向 - 仅适用于所有网址

node.js - TS2307 : Cannot find module 'express'

javascript - (nodeJS) S3 对象的内容类型 : manually set to 'image/jpeg' but in S3 console comes up as 'application/octet'

amazon-web-services - AWS CloudFormer 支持哪些 AWS 服务?

amazon-web-services - AWS DynamoDB 受限制的写入请求处理