axios
ポーロフォリオでよく使われているイメージがあったので、現段階の知識の整理のためにブログを書きます。
サーバーサイドではnode.jsを使用し、フロントサイドではXHMLhttpRequestを使っているのがaxios
Axiosとは
Httpのやり取りにおける仲介役立ち位置。
axiosを使うことで、jsonのやり取りが容易になり、APIを叩きやすくする。
-
引用(github-axios)
Features
どういった場面で使われるか
非同期にHTTP通信を行いたいとき
インストール
Using npm:
$npminstall axios
Using bower:
$ bowerinstall axios
Using yarn:
$yarnadd axios
Using jsDelivr CDN:
<scriptsrc="<https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js>"></script>
Using unpkg CDN:
<scriptsrc="<https://unpkg.com/axios/dist/axios.min.js>"></script>
使用例
GET
requestを行う場合
const axios =require('axios');
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
asyncfunctiongetUser() {
try {
const response =await axios.get('/user?ID=12345');
console.log(response);
}catch (error) {
console.error(error);
}
}
例その2
<body>
<input type ="text" placeholder="githubアカウント名" id="github-name">
<button onclick="fetchRepositories()">リポジトリ取得</button>
<!--buttonタグに直接埋め込み-->
<ul id="repository-lists">
</ul>
<script src="<https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js>"></script>
<script>
const fetchRepositories = async () => {
const githubName = document.querySelector("#github-name").value;
try{
//Httpリクエストをawait axiosを使って叩いている
const res = await axios.get(`https://api.github.com/users/${githubName}/repos`);
//repository-listsのDOMを取得
const repositoryLists = document.querySelector('#repository-lists')
//取得したDOMの中身にresファンクションでブラウザから取ってきたデータをa hrefで格納する。
repositoryLists.innerHTML = res.data.map(repository=>{
//''と``を間違えるだけでエラーが出るから注意
return `<li><a href="${repository.html_url}">${repository.name}</a></li>`;
}).reduce((a,b) => {
return a + b;
});
} catch {
alert("エラー");
}
};
</script>