我正在尝试在 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/