Reputation: 412
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?
Upvotes: 1
Views: 593
Reputation: 8593
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))
};
Upvotes: 1