1

I am trying to set up an HTTPS call inside my lambda function. I have gone through a number of tutorials but I obviously don't understand it well enough.

I am just using a basic example to a chuck norris jokes 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))

};

Best I can get is for it to return "Success" Using the .then() chaining doesn't produce any results, neither does trying to work with the "res" return in the reslove function.

I have no idea what else to try...

Any suggestions?

1 Answer 1

1

you can use response.end event to resolve the 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))
};
Sign up to request clarification or add additional context in comments.

1 Comment

if you see my answer, i have removed the word "Sucess" from the code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.