2
4

More than 1 year has passed since last update.

axiosについて

Last updated at Posted at 2022-09-06

axiosとは

  • HTTP非同期通信ライブラリー。
  • バックエンドとデータを受け渡しをする際に使うライブラリー。
  • バックエンドと通信できるURLに非同期でアクセスしてget, post, update, deleteの作業を行うことができる。

axiosのメリット

  • バックエンドとの通信時に自動的にデータをjson形式に変換する。
  • リクエストをキャンセルすることができる。
  • 幅広いブラウザー&バージョンに対応。
  • アップロードやダウンロード時に進行状況の情報を取得することができる。

axiosのデメリット

  • 外部のライブラリーであるため、インストールが必要

axiosの特徴

  • axiosから要請したレスポンスはPromiseのオブジェクトである。
  • そのため、以下の使用方法のようにasyncとawaitを使って簡潔に記述することができる。

axiosの使用方法

  • axiosをインストールして以下のように利用することができる。
javascript
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345') //非同期でURLにアクセスしてバックエンドからデータを受ける。
    console.log(response)
  } catch (error) {
    console.error(error)
  }
}

例外処理

バックエンドとのやりとり中にはさまざまな例外が発生するため、例外処理を行う必要がある。
やり方としては try & catchawait & catchが挙げられ、以下のように使うことができる。

try & catchパターン

javascript
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345') //非同期でURLにアクセスしてバックエンドからデータを受ける。
    console.log(response)
  } catch (error) {
    console.error(error)
  }
}

await & catchパターン

javascript
async function getUser() {
  const res = await axios.get('/user?ID=12345')
  .catch((err) => {
    return err
  })
}

axios以外の非同期処理方法

実は非同期処理にはaxios以外にも複数あり、代表的にはfetch, jQueryがあり、それぞれ使い方は異なるが、基本概念は変わらない。なお、fetchはES6から使えるようになった非同期処理のためのjavascriptの内に組み込まれたAPIである。以下は、axiosとfetchの違いについてまとめたものである。

axiosとfetchとの違い

Axios Fetch
インストール 必要 いらない
JSON変換 自動変換 手動的に変換する必要あり
requestのキャンセル設定 可能 不可能
ダウンロードプログレス 利用可能 不可能

fetchの使い方

< GET >

javascript
const url = '/user?ID=12345';
fetch(url)
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => {
        console.log(error);
    });

< POST >

javascript
const url = '/user?ID=12345';
const params = {
    name: '山田太郎',
    email: 'taro@example.com',
    password: 'secret'
};
fetch(url, {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(params)
})
.then(response => response.json())
.then(data => {
    console.log(data);
})
.catch(error => {
    console.log(error);
});

jQueryの使い方

< GET >

javascript
const url = '/user?ID=12345';
$.get(url)
    .done(data => {
        console.log(data);
    })
    .fail(error => {
        console.log(error);
    });

< POST >

javascript
const url = '/user?ID=12345';
const params = {
    name: '山田太郎',
    email: 'taro@example.com',
    password: 'secret'
};
$.post(url, params)
    .done(data => {
        console.log(data);
    })
    .fail(error => {
        console.log(error);
    });
2
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4