1分でわかるJavaScriptライブラリaxiosの超簡単な使い方

axiosとは

HTTP通信を超簡単に行うことができるJavaScriptライブラリ。

HTTP通信と言うと用途がわかりづらいが、主にJSONの取得に利用されることが多い。

axiosの読み方

axiosは「アクシオス」と読む。元々はギリシャ語で「値する」という意味。

axiosの使い方

axios.min.jsを読み込んでaxios.getでJSONを読み込んで.then(res => res.data)とすればJSONのデータを取得できる。

<html>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(res => console.log(res.data))
</script>
</html>

axiosでJSON取得サンプル

JavaScriptのfetchだとこのようになる。比べるとfetchよりもaxiosのコードの方が短く簡潔になっている。また、fetchと異なりほとんどのブラウザで使用可能だ。

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(res => res.json())
  .then(json => console.log(json))

catchはエラー・finallyは常時

then以外にもcatchとfinallyがあり、catchはエラー、finallyは成功とエラーのどちらの結果でも実行される。

axios.get('https://jsonplaceholder.typicode.com/todos/1x')
  .then(res => console.log(res.data))
  .catch(err => console.error(err))
  .finally(res => console.log('finally'))

axiosのcatch・finallyサンプル