fetch API — サーバーとのデータ送受信
このトピックを終えると
fetchを使ってサーバーにリクエストを送信し、レスポンスを処理する基本的なパターンを理解できます。
fetchとは
fetchはブラウザに組み込まれているHTTPリクエスト関数です。サーバーにデータをリクエストしたり、送信したりするときに使用します。Promiseを返すため、async/awaitと組み合わせて使用します。
const response = await fetch("/api/users");
const data = await response.json();
console.log(data);3つのステップです:リクエスト送信 → レスポンス受信 → データ解析。
GETリクエスト
データを取得するときに使用します。デフォルトがGETなので、明示的に指定する必要はありません:
const res = await fetch("/api/users");
const users = await res.json();クエリパラメータが必要な場合は、URLに追加します:
const res = await fetch("/api/users?page=2&limit=10");POSTリクエスト
データを送信するときに使用します:
const res = await fetch("/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "Alice",
email: "alice@example.com",
}),
});
const created = await res.json();method、headers、bodyを2番目の引数として渡します。bodyには、JSON.stringifyで変換した文字列を入れます。
レスポンスステータスの確認
fetchは、HTTPエラー(404、500)が発生した場合でもエラーをスローしません。ネットワーク自体が失敗した場合にのみエラーをスローします。
const res = await fetch("/api/users/999");
console.log(res.status); // 404
console.log(res.ok); // false (statusが200-299の範囲外)そのため、手動で確認する必要があります:
const res = await fetch("/api/users");
if (!res.ok) {
throw new Error(`HTTP error: ${res.status}`);
}
const data = await res.json();エラー処理のパターン
async function fetchUsers() {
try {
const res = await fetch("/api/users");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (error) {
if (error instanceof TypeError) {
console.log("ネットワーク接続に失敗しました");
} else {
console.log("リクエストに失敗しました:", error.message);
}
return [];
}
}TypeErrorは、ネットワーク自体が利用できない場合に発生します(サーバーダウン、オフライン)。
レスポンスデータの形式
const json = await res.json(); // JSON → オブジェクト
const text = await res.text(); // テキスト
const blob = await res.blob(); // バイナリ(画像など).json()、.text()、.blob()のうち1つだけを呼び出すことができます。一度読み込んだレスポンスボディは、再度読み込むことはできません。
重要なポイント
fetchはブラウザに組み込まれているHTTPリクエスト関数であり、Promiseを返します。 HTTPエラー(404、500)が発生した場合でも、自動的にエラーをスローしないため、res.okを確認する必要があります。 GETはデータの取得、POSTはデータの送信に使用します。