フェッチAPIでJavaScriptのリクエストをモダンにこなす

フェッチAPIでJavaScriptのリクエストをモダンにこなす

フェッチAPIは、非同期のHTTPリクエストを簡潔に記述できるJavaScriptの標準機能です。本記事では、フェッチAPIの基本から高度な使い方までを網羅し、リクエストの実践的な活用方法を詳細に解説します。

フェッチAPIの基本

フェッチAPIを使用してデータを取得します。

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

GETリクエスト

フェッチAPIのデフォルトメソッドを使ったシンプルなGETリクエスト。

fetch('https://api.example.com/users')
  .then(response => response.json())
  .then(users => console.log(users))
  .catch(error => console.error('Error fetching users:', error));

POSTリクエスト

リクエストボディを含むデータを送信する例。

fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: 'John Doe', age: 30 })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

ヘッダーの追加

カスタムヘッダーをリクエストに追加します。

fetch('https://api.example.com/data', {
  headers: {
    'Authorization': 'Bearer your-token-here',
    'Content-Type': 'application/json',
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

非同期関数とフェッチAPI

async/awaitを使った非同期処理の簡潔な記述。

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();

タイムアウト処理

フェッチAPIでタイムアウトを実装する方法。

const fetchWithTimeout = (url, options, timeout = 5000) => {
  return Promise.race([
    fetch(url, options),
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('Request timed out')), timeout)
    )
  ]);
};

fetchWithTimeout('https://api.example.com/data', {}, 3000)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

エラーハンドリング

ステータスコードをチェックしてエラーを処理します。

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

ファイルのアップロード

ファイルをアップロードするリクエスト。

const formData = new FormData();
formData.append('file', fileInput.files[0]);

fetch('https://api.example.com/upload', {
  method: 'POST',
  body: formData
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

ストリーム処理

ストリームを利用して大きなレスポンスデータを処理します。

fetch('https://api.example.com/large-data')
  .then(response => {
    const reader = response.body.getReader();
    return new ReadableStream({
      start(controller) {
        function push() {
          reader.read().then(({ done, value }) => {
            if (done) {
              controller.close();
              return;
            }
            controller.enqueue(value);
            push();
          });
        }
        push();
      }
    });
  })
  .then(stream => new Response(stream))
  .then(response => response.text())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

クロスオリジンリクエスト

CORSに対応するためのリクエスト設定。

fetch('https://api.example.com/data', {
  mode: 'cors',
  headers: {
    'Content-Type': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

リトライロジックの実装

失敗したリクエストをリトライする仕組み。

async function fetchWithRetry(url, options, retries = 3) {
  for (let i = 0; i < retries; i++) {
    try {
      const response = await fetch(url, options);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      if (i < retries - 1) {
        console.warn(`Retrying... (${i + 1})`);
      } else {
        throw error;
      }
    }
  }
}

fetchWithRetry('https://api.example.com/data', {}, 3)
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

まとめ

フェッチAPIを活用することで、HTTPリクエストを簡潔かつ柔軟に記述できます。非同期処理やエラーハンドリング、ファイルアップロードなど、さまざまなユースケースに対応可能です。モダンなJavaScriptの開発において必須の技術として活用してください。