AJAX、Fetch、Axiosによるデータ取得の比較

jQuery.ajaxの特徴

jQuery.ajaxはネイティブのXHRをラッピングし、JSONPサポートを追加した非同期通信手段。以下が基本的な使用例。

$.ajax({
    endpoint: 'https://api.example.com/data',
    parameters: { id: 123 },
    requestType: 'GET',
    expectedFormat: 'json',
    asyncOperation: true,
    cacheControl: false,
    onSuccess: function(response) {
        console.log('取得成功:', response);
    },
    onError: function(error) {
        console.error('通信エラー:', error);
    }
});

課題点:

  • MVCアーキテクチャに特化し、現代のMVVMフローには不向き
  • XHRの限界を引き継ぐため、Fetch APIなどの代替技術が存在
  • ライブラリ全体を導入する必要があるため、バンドルサイズの最適化が困難
  • イベント駆動型の非同期モデルが直感的でない

Fetch APIの特徴

ネイティブのリソース取得メカニズムで、Promiseベースの設計が特徴。ES6以降のブラウザで利用可能。

// GETリクエスト例
fetch(`https://api.example.com/users?${new URLSearchParams({ name: 'Alice' })}`)
  .then(response => response.json())
  .then(data => {
    console.log('取得データ:', data);
  });

// POSTリクエスト例
fetch('https://api.example.com/register', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ username: 'bob', email: 'bob@example.com' })
})
  .then(response => response.json())
  .then(data => {
    console.log('登録結果:', data);
  });

メリット:

  • セマンティックなインターフェース設計
  • Request/Responseオブジェクトの柔軟な操作が可能
  • XHRから独立したES規格に基づく実装
  • Promiseチェーンとasync/awaitの併用が可能

Axiosの特徴

HTTPクライアントライブラリで、Promise APIとCSRF保護機能を備える。以下が基本的な使用例。

// GETリクエスト例
axios.get('https://api.example.com/profile', {
  params: { userId: '456' }
})
.then(response => {
  console.log('プロフィール情報:', response.data);
})
.catch(error => {
  console.error('取得失敗:', error.message);
});

// POSTリクエスト例
axios.post('https://api.example.com/login', {
  email: 'user@example.com',
  password: 'securepass'
})
.then(response => {
  console.log('認証結果:', response.status);
})
.catch(error => {
  console.error('認証エラー:', error.response?.status);
});

主な機能:

  • Node.js環境でのHTTPリクエストサポート
  • JSONデータの自動シリアライズ/デシリアライズ
  • 複数リクエストの並列処理(allメソッド)
  • クライアントサイドでのCSRF防止機構

複数リクエストの連携例

axios.get('https://api.example.com/check')
  .then(response => {
    if (response.data.status === 'active') {
      return axios.post('https://api.example.com/activate', {
        token: 'abc123'
      });
    }
    throw new Error('ステータス異常');
  })
  .then(response => {
    console.log('アクティベート成功:', response.data);
  })
  .catch(error => {
    console.error('処理失敗:', error.message);
  });

並列処理の例

const [userResponse, settingResponse] = await Promise.all([
  axios.get('https://api.example.com/user'),
  axios.get('https://api.example.com/settings')
]);

if (userResponse.data.isValid && settingResponse.data.isReady) {
  console.log('初期化完了');
} else {
  console.warn('初期化条件未満');
}

タグ: jQuery Axios FetchAPI HTTP通信 Promise

7月4日 23:35 投稿