要解决“AWS Lambda 无法进行 HTTP 调用”的问题,您可以使用 AWS SDK 来进行 HTTP 请求。以下是一个使用 AWS Lambda 和 Node.js 的示例代码,演示如何进行 HTTP 调用:
const AWS = require('aws-sdk');
const https = require('https');
exports.handler = async (event, context) => {
// 设置 AWS SDK 配置
AWS.config.update({
region: 'us-east-1'
// 根据您的需求进行配置
});
// 创建 HTTP 请求选项
const options = {
hostname: 'api.example.com',
port: 443,
path: '/endpoint',
method: 'GET',
headers: {
'Content-Type': 'application/json'
// 根据您的需求添加其他头信息
}
};
// 创建 Promise 对象,以便异步处理
const promise = new Promise((resolve, reject) => {
// 发起 HTTP 请求
const req = https.request(options, (res) => {
let responseBody = '';
// 接收响应数据
res.on('data', (chunk) => {
responseBody += chunk;
});
// 响应完成后处理数据
res.on('end', () => {
resolve(responseBody);
});
});
// 处理错误
req.on('error', (error) => {
reject(error);
});
// 发送请求
req.end();
});
try {
// 等待 Promise 对象的结果并返回
const response = await promise;
return response;
} catch (error) {
throw new Error(`HTTP 请求失败: ${error}`);
}
};
在上述示例中,我们使用 https 模块来进行 HTTP 请求,并使用 AWS SDK 来配置 AWS 相关设置。您可以根据自己的需求,修改 options 对象来设置请求的目标主机、端口、路径、方法和头信息。最后,在 Lambda 函数中使用异步函数和 await 关键字等待 Promise 对象的结果,并返回响应数据。
请注意,在使用此代码时,您需要将 api.example.com 替换为您要请求的实际主机,并根据需要修改其他配置。