ソースコード
axiosでGitHub APIを叩くサンプルです。自分(k163377)のリポジトリ情報を取得し、その名前を書き出します。
一瞬詰まった点としては、取得成功時に呼ばれる関数内でエラーを出した場合、処理はそこで中断されてエラー処理関数が呼び出されることがあります。まあaxiosの呼び出しがtry-catch文だと見れば自然ですね。
処理の規模がここまで小さいならラムダ式使ってもよさそうです。
<!DOCTYPE html> <html> <meta charset="UTF-8";> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> let baseUrl="https://api.github.com/users/" function main(){ let url = baseUrl + "k163377" + "/repos" console.log(url) axios .get(url) .then(getReposSuccess) .catch(getReposFailure) } /* 取得成功時 */ function getReposSuccess(response) { console.log(response.data) for(let repo of response.data) { console.log(repo.name) } } /* 取得失敗か成功時関数でのエラー時 */ function getReposFailure(error) { /* エラー処理 */ } window.onload = main </script> </html>
実行結果