Cloud Resume Challenge:Fetch API调用AWS接口获取访客计数出错求助
Cloud Resume Challenge:API Gateway调用访客计数问题
长期潜水首次发帖,正在完成Cloud Resume Challenge的访客计数模块——已经搭建了关联Lambda函数的AWS API Gateway,但用JavaScript调用API获取计数时一直失败,附上当前代码和错误信息,求指引。
当前代码
<article> <script> fetch('https://5cabfxax81.execute-api.ap-southeast-2.amazonaws.com/Prod/') .then((response => response.json())) .then(data => console.log(data)) .then(response=> {document.getElementById("counter").innerHTML = data.count}); </script> <p class="subDetails">You are visitor number <span id="counter">loading...</span></p> <p></p> </article>
错误信息
ReferenceError: data is not defined
问题分析与解决方案
你的代码核心问题是Promise链式调用的数据流断裂:
- 第二个
then里只执行了console.log(data),但没有return data,导致下一个then接收的参数是undefined - 第三个
then里尝试访问data.count,但此时data根本不存在,直接抛出引用错误
修正后的代码
<article> <script> fetch('https://5cabfxax81.execute-api.ap-southeast-2.amazonaws.com/Prod/') // 解析响应为JSON .then(response => response.json()) // 合并逻辑:打印数据+更新DOM .then(data => { console.log(data); document.getElementById("counter").innerHTML = data.count; }) // 添加错误捕获,处理请求失败场景 .catch(error => { console.error('请求访客计数失败:', error); document.getElementById("counter").innerHTML = '加载失败'; }); </script> <p class="subDetails">You are visitor number <span id="counter">loading...</span></p> <p></p> </article>
额外检查点
- CORS配置:如果你的简历页面和API Gateway不在同一域名,必须在AWS控制台给API Gateway开启CORS,允许前端页面的域名发起请求(测试阶段可临时允许所有
*) - Lambda返回格式:确保Lambda函数返回的JSON结构包含
count字段,比如{"count": 123} - API Gateway部署状态:确认API已经部署到
Prod阶段,且调用URL正确
内容的提问来源于stack exchange,提问作者Will Garbutt
相关产品推荐
相关产品推荐

