Axios

Axiosは、ブラウザとNode.js環境の両方で使用できるPromiseベースのHTTPクライアントライブラリです。主にWebアプリケーションでサーバーとのHTTP通信を簡単に処理するために使用されます。

== 概要 ==

Axiosは2014年に初めてリリースされ、現在GitHubで活発に管理されているオープンソースプロジェクトです。XMLHttpRequestインターフェースをベースとしており、JSONデータ変換、リクエスト/レスポンスインターセプト、自動変換、クライアントサイドXSRF保護など、さまざまな機能を提供します。

== 主な機能 ==

  • Promise APIサポート: 非同期リクエスト処理のためのPromiseベースのAPIを提供します。
  • リクエスト/レスポンスインターセプト: HTTPリクエストとレスポンスをインターセプトして変換したりログを記録したりできます。
  • 自動JSON変換: サーバーから受け取ったJSONデータを自動的にJavaScriptオブジェクトに変換します。
  • リクエストのキャンセル: リクエストをキャンセルできる機能を提供します。
  • 同時リクエスト: 複数のリクエストを同時に実行し、結果を処理できます。
  • CSRF保護: クライアントサイドのクロスサイトリクエストフォージェリ保護をサポートします。
  • ブラウザ/Node.js互換: 両方の環境で使用可能です。

== インストール ==

=== npm ===

bash

npm install axios

=== yarn ===

bash

yarn add axios

=== CDN ===

html

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

== 基本的な使い方 ==

=== GETリクエスト ===

javascript

axios.get('/user?ID=12345')

.then(function (response) {

console.log(response.data);

})

.catch(function (error) {

console.log(error);

});

=== POSTリクエスト ===

javascript

axios.post('/user', {

firstName: 'John',

lastName: 'Doe'

})

.then(function (response) {

console.log(response);

})

.catch(function (error) {

console.log(error);

});

=== 同時リクエスト ===

javascript

function getUserAccount() {

return axios.get('/user/12345');

}

function getUserPermissions() {

return axios.get('/user/12345/permissions');

}

axios.all([getUserAccount(), getUserPermissions()])

.then(axios.spread(function (acct, perms) {

// 両方のリクエストが完了

}));

== 設定オプション ==

Axiosリクエスト時には、さまざまな設定オプションを指定できます:

javascript

{

// リクエストURL

url: '/user',

// リクエストメソッド (デフォルト: 'get')

method: 'get',

// ベースURL

baseURL: 'https://api.example.com',

// リクエストヘッダー

headers: {'X-Requested-With': 'XMLHttpRequest'},

// リクエストパラメータ

params: {

ID: 12345

},

// リクエストデータ (POST, PUT, PATCHリクエスト時に使用)

data: {

firstName: 'John'

},

// リクエストタイムアウト (ミリ秒)

timeout: 1000,

// レスポンスタイプ (デフォルト: 'json')

responseType: 'json'

}

== インターセプター ==

リクエストやレスポンスをthenまたはcatchで処理する前にインターセプトできます:

javascript

// リクエストインターセプター

axios.interceptors.request.use(function (config) {

// リクエスト前の処理

return config;

}, function (error) {

// リクエストエラー処理

return Promise.reject(error);

});

// レスポンスインターセプター

axios.interceptors.response.use(function (response) {

// レスポンスデータ処理

return response;

}, function (error) {

// レスポンスエラー処理

return Promise.reject(error);

});

== エラー処理 ==

Axiosではさまざまな方法でエラーを処理できます:

javascript

axios.get('/user/12345')

.catch(function (error) {

if (error.response) {

// サーバーが2xxの範囲外のステータスコードで応答

console.log(error.response.data);

console.log(error.response.status);

console.log(error.response.headers);

} else if (error.request) {

// リクエストは行われたが応答を受信しなかった

console.log(error.request);

} else {

// リクエスト設定中にエラーが発生

console.log('Error', error.message);

}

console.log(error.config);

});

== キャンセルトークン ==

リクエストをキャンセルするためにキャンセルトークンを使用できます:

javascript

const CancelToken = axios.CancelToken;

const source = CancelToken.source();

axios.get('/user/12345', {

cancelToken: source.token

}).catch(function (thrown) {

if (axios.isCancel(thrown)) {

console.log('Request canceled', thrown.message);

} else {

// エラー処理

}

});

// リクエストをキャンセル

source.cancel('Operation canceled by the user.');

== インスタンスの作成 ==

カスタム設定を持つAxiosインスタンスを作成できます:

javascript

const instance = axios.create({

baseURL: 'https://api.example.com',

timeout: 1000,

headers: {'X-Custom-Header': 'foobar'}

});

== ブラウザサポート ==

Axiosは以下のブラウザをサポートしています:

  • Chrome
  • Firefox
  • Safari
  • Edge
  • Internet Explorer 11

== 関連プロジェクト ==

  • axios-retry: リクエスト失敗時の自動再試行機能
  • axios-mock-adapter: テスト用のモッキングアダプター
  • vue-axios: Vue.jsとの統合
  • react-axios: Reactコンポーネント

== 参考資料 ==

[[カテゴリ:JavaScriptライブラリ]]

[[カテゴリ:HTTPクライアント]]

[[カテゴリ:オープンソースソフトウェア]]