Fetch API: HTTP通信の標準
XMLHttpRequest の代わりに使う、モダンなAPI。
fetch
HTTP リクエストを送る標準API。
Response
サーバーからの応答を表すオブジェクト。
AbortController
リクエストをキャンセルする仕組み。
fetch基礎
// 基本的な fetchconst response = await fetch('/api/users');const users = await response.json();
// POSTリクエストconst res = await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Alice' })});Bad
// ❌ Bad: エラーハンドリングなしconst res = await fetch('/api/data');const data = await res.json(); // 404でも実行されるGood
// ✅ Good: ステータスをチェックconst res = await fetch('/api/data');if (!res.ok) { throw new Error(`HTTP ${res.status}`);}const data = await res.json();よくあるパターン
// 並列リクエストconst [users, products] = await Promise.all([ fetch('/api/users').then(r => r.json()), fetch('/api/products').then(r => r.json())]);
// タイムアウト付き (AbortController)const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), 5000);
try { const res = await fetch('/api/slow', { signal: controller.signal });} catch (e) { if (e.name === 'AbortError') { console.log('Timeout!'); }} finally { clearTimeout(timeoutId);} Tip: Promise.all で複数リクエストを並列化。
合格ライン
GET/POST リクエストを送れる
res.ok でエラーチェックできる
演習課題
課題1: GET リクエスト
fetch で GET リクエストを送信してください。
課題2: POST リクエスト
fetch で JSON を POST してください。