SvelteKit中TypeError: fetch failed错误修复求助
修复SvelteKit调用PokeAPI的TypeError: fetch failed问题
常见问题排查
- 先确认PokeAPI的请求URL是否正确,官方基础地址是
https://pokeapi.co/api/v2/pokemon,别写错拼写或漏了HTTPS协议 - SvelteKit的
+page.ts里的load函数必须用async/await处理异步逻辑,不能直接返回未处理的Promise - 必须添加错误捕获,否则任何网络波动或API返回异常都会直接抛出
fetch failed错误
修复后的+page.ts代码
import type { PageLoad } from './$types'; export const load: PageLoad = async ({ fetch }) => { try { // 请求20只宝可梦的列表数据 const res = await fetch('https://pokeapi.co/api/v2/pokemon?limit=20'); // 先检查响应状态,非200状态直接抛错 if (!res.ok) { throw new Error(`请求失败: ${res.status}`); } const listData = await res.json(); // 批量请求每只宝可梦的详细信息(头像、类型等) const pokemonDetails = await Promise.all( listData.results.map(async (pokemon: { url: string }) => { const detailRes = await fetch(pokemon.url); return detailRes.json(); }) ); return { pokemon: pokemonDetails }; } catch (err) { console.error('获取宝可梦数据出错:', err); // 返回空数组避免页面崩溃 return { pokemon: [] }; } };
修复后的+page.svelte代码(实现卡片式展示)
<script lang="ts"> import type { PageData } from './$types'; export let data: PageData; </script> <div class="pokemon-grid"> {#each data.pokemon as poke} <div class="poke-card"> <img src={poke.sprites.front_default} alt={poke.name} /> <h3>{poke.name.charAt(0).toUpperCase() + poke.name.slice(1)}</h3> <p>编号: #{poke.id.toString().padStart(3, '0')}</p> <div class="types"> {#each poke.types as typeItem} <span class="type-tag">{typeItem.type.name}</span> {/each} </div> </div> {:else} <p>加载失败啦,刷新试试?</p> {/each} </div> <style> .pokemon-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 1.5rem; padding: 2rem; } .poke-card { background: #fff; border-radius: 10px; padding: 1.2rem; text-align: center; box-shadow: 0 3px 6px rgba(0,0,0,0.1); transition: transform 0.2s; } .poke-card:hover { transform: translateY(-5px); } .poke-card img { width: 130px; height: 130px; margin: 0 auto 1rem; } .types { display: flex; gap: 0.6rem; justify-content: center; margin-top: 0.8rem; } .type-tag { padding: 0.3rem 0.7rem; border-radius: 20px; color: #fff; font-size: 0.85rem; /* 可根据宝可梦类型自定义背景色,比如草系#7AC74C、火系#EE8130 */ background: #7AC74C; } </style>
核心修复说明
- 使用SvelteKit提供的
fetch(从load函数参数中获取),而非全局fetch,确保服务器端渲染和客户端都能正常工作 - 补充完整的
try/catch逻辑,捕获网络错误和API返回异常,避免页面直接崩溃 - 检查响应的
ok状态码,处理404、500这类HTTP错误 - 渲染时添加
{:else}分支,给用户友好的加载失败提示
内容的提问来源于stack exchange,提问作者Thong Doan
相关产品推荐
相关产品推荐

