使用asyncFetch调用SWAPI接口时控制台报错,求解决方法
SWAPI接口调用故障修复方案
- 核心故障:接口域名已迁移
SWAPI官方服务域名早已从swapi.co升级为swapi.dev,原域名已停止服务,所有请求都会直接失败,这是控制台报错的主要原因。 - 代码瑕疵:HTML拼接语法错误
渲染影视数据的逻辑中,<p class=""text-center>多写了一个冗余双引号,会导致最终插入页面的HTML结构异常,样式渲染出错。 - 优化建议:新增异常捕获逻辑
现有异步请求没有配置错误捕获规则,请求失败时会直接抛出未处理异步错误,无法快速定位故障。
修复后完整代码
const results = document.querySelector("#results"); async function asyncFetch(value) { // 新增异常捕获 try { // 替换为新的官方接口域名 const res = await fetch(`https://swapi.dev/api/${value}/`); // 校验请求状态 if (!res.ok) throw new Error(`接口响应错误:${res.status}`) const data = await res.json(); displayResults(data, value); } catch (err) { results.innerHTML = `<div class="p-3 m-3 text-danger">数据加载失败,请稍后重试</div>` console.error('请求故障:', err) } } function displayResults(data, value) { let output = ""; if (value === 'films') { data.results.forEach(item => { output += ` <div class="card p-3 m-3" style="opacity:.8"> <h4 class="card-title text-center">${item.title}</h4> <div class="card-content"> <span style="text-decoration:underline">Producer</span>: ${item.producer}<br> <span style="text-decoration:underline">Director</span>: ${item.director}<br> <span style="text-decoration:underline">Release Date</span>: ${item.release_date}<br> <!-- 修复冗余引号的问题 --> <p class="text-center">${item.opening_crawl}</p> </div> </div> ` }) } if (value === 'people') { data.results.forEach(item => { output += ` <div class="card p-3 m-3" style="opacity:.8"> <h4 class="card-title text-center">${item.name}</h4> <div class="card-content"> <span style="text-decoration:underline">Height</span>: ${item.height}<br> <span style="text-decoration:underline">Birth Year</span>: ${item.birth_year}<br> <span style="text-decoration:underline">Skin Color</span>: ${item.skin_color}<br> </div> </div> ` }) } if (value === 'vehicles') { data.results.forEach(item => { output += ` <div class="card p-3 m-3" style="opacity:.8"> <h4 class="card-title text-center">${item.name}</h4> <div class="card-content"> <span style="text-decoration:underline">Capacity</span>: ${item.cargo_capacity} kg<br> <span style="text-decoration:underline">Model</span>: ${item.model}<br> <span style="text-decoration:underline">manufacturer</span>: ${item.manufacturer}<br> <span style="text-decoration:underline">Vehicle Class</span>: ${item.vehicle_class}<br> </div> </div> ` }) } results.innerHTML = output; } // event listener for buttons document.querySelector("#buttons").addEventListener("click", e => { asyncFetch(e.target.textContent.trim().toLowerCase()); });
内容的提问来源于stack exchange,提问作者Michael Delcore
相关产品推荐
相关产品推荐

