
axiosとは
HTTP通信を超簡単に行うことができるJavaScriptライブラリ。
HTTP通信と言うと用途がわかりづらいが、主にJSONの取得に利用されることが多い。
axiosの読み方
axiosは「アクシオス」と読む。元々はギリシャ語で「値する」という意味。
axiosの使い方
axios.min.jsを読み込んでaxios.getでJSONを読み込んで.then(res => res.data)とすればJSONのデータを取得できる。
1 2 3 4 5 6 7 | < html > < script > axios.get('https://jsonplaceholder.typicode.com/todos/1') .then(res => console.log(res.data)) </ script > </ html > |
JavaScriptのfetchだとこのようになる。比べるとfetchよりもaxiosのコードの方が短く簡潔になっている。また、fetchと異なりほとんどのブラウザで使用可能だ。
1 2 3 | .then(res => res.json()) .then(json => console.log(json)) |
catchはエラー・finallyは常時
then以外にもcatchとfinallyがあり、catchはエラー、finallyは成功とエラーのどちらの結果でも実行される。
1 2 3 4 | .then(res => console.log(res.data)) . catch (err => console.error(err)) .finally(res => console.log( 'finally' )) |