首次编写API Fetch请求无法拉取数据,报response未定义错误如何解决
报错修复说明
该错误是变量拼写不一致导致的引用问题:
- 你调用fetch后给返回值赋值的变量名写为
respone(缺失字母s) - 后续调用
.json()方法时使用的变量名为response,两个名称不匹配,因此程序找不到对应变量抛出未定义报错
你只需要把fetch行的变量名修改为正确拼写即可,修复后的完整代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title> API Test </title> </head> <body> <h1>Where is the ISS? </h1> <p>Latitude: <span id="lat"></span><br /> Longitude: <span id="lon"></span></p> <script> const iss_url = 'https://api.wheretheiss.at/v1/satellites/25544'; async function getISS() { // 修正变量拼写错误 const response = await fetch(iss_url); const data = await response.json(); const { latitude, longitude } = data; document.getElementById('lat').textContent = latitude; document.getElementById('lon').textContent = longitude; } getISS(); </script> </body> </html>
可选优化建议:
- 补充了原代码中缺失的
</p>闭合标签,避免HTML结构解析异常 - 你也可以给异步请求增加try/catch捕获,处理接口请求失败的场景:
async function getISS() { try { const response = await fetch(iss_url); const data = await response.json(); const { latitude, longitude } = data; document.getElementById('lat').textContent = latitude; document.getElementById('lon').textContent = longitude; } catch (err) { console.error('请求ISS位置失败:', err) } }
内容的提问来源于stack exchange,提问作者Tyler Coleman
相关产品推荐
相关产品推荐

