如何让AWS Lambda执行结果自动展示为网页或文本实体?
问题描述
我使用Node.js 16.x编写了如下Lambda函数:
function getScore(arr) { let temp; let i = Math.floor((Math.random() * arr.length)); temp = arr[i]; console.log(i); console.log(temp); return temp; } const arrScores = [700, 820, 640, 460, 726, 850, 694, 721, 556]; exports.handler = (event, context, callback) => { let creditScore = getScore(arrScores); callback(null, "Credit score pulled is: " + creditScore + "."); };
执行结果示例如下:
Response:
"Credit score pulled is: 556."
我希望Lambda执行后能自动展示该结果,无论通过浏览器打开还是其他方式均可。我是纯新手,曾搜索“lambda node.js write response in browser”等关键词寻求解决办法,盼得到帮助。
解决方案
Lambda本身无法直接被浏览器访问,你需要给它配置API Gateway触发器,这样就能通过URL在浏览器里打开并看到结果。具体步骤如下:
- 修改Lambda函数的返回格式
浏览器需要标准的HTTP响应格式,原函数的返回只是字符串,要改成符合API Gateway要求的结构:
function getScore(arr) { let temp; let i = Math.floor((Math.random() * arr.length)); temp = arr[i]; console.log(i); console.log(temp); return temp; } const arrScores = [700, 820, 640, 460, 726, 850, 694, 721, 556]; exports.handler = (event, context, callback) => { let creditScore = getScore(arrScores); const response = { statusCode: 200, headers: { "Content-Type": "text/plain" // 让浏览器识别为文本内容 }, body: "Credit score pulled is: " + creditScore + "." }; callback(null, response); };
- 在AWS控制台配置API Gateway触发器
- 打开你的Lambda函数页面,找到“触发器”标签,点击“添加触发器”
- 选择“API Gateway”作为触发器类型
- 配置选项:
- API类型选“HTTP API”(比REST API更简单,适合新手)
- 安全选项选“开放”(测试用,后续可根据需求调整权限)
- 点击“添加”完成配置
- 测试访问
配置完成后,Lambda页面会生成一个API的URL,复制这个URL到浏览器里打开,就能直接看到返回的信用分数结果了。
内容的提问来源于stack exchange,提问作者M. Richartz
相关产品推荐
相关产品推荐

