以下是一个使用AWS API Gateway和Lambda函数的示例代码,其中将整个Lambda响应对象作为消息体返回给API Gateway。
// Lambda函数代码
exports.handler = async (event, context) => {
try {
// 处理逻辑...
// 构建响应对象
const response = {
statusCode: 200,
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ message: "Hello, World!" })
};
return response;
} catch (error) {
// 处理错误逻辑...
// 构建错误响应对象
const errorResponse = {
statusCode: 500,
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ error: "Internal Server Error" })
};
return errorResponse;
}
};
配置AWS API Gateway时,选择“Integration type”为Lambda函数,并将Lambda函数与API Gateway集成。确保在API Gateway的“Integration Response”中设置正确的“Content-Type”响应头。这样,API Gateway将整个Lambda响应对象作为消息体返回给调用方。
注意:根据你的需求,你可能需要修改代码中的响应对象和错误处理逻辑。