Axios.jsでajaxするコードGETもPOSTも可能
概要
javascript で API通信を行うためのもの
コード
- html
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
- javascript
async function ajax(url, json, method, error_method, http_method = "post") {
switch (http_method) {
case "post":
await axios
.create({
xsrfHeaderName: 'X-CSRF-Token',
withCredentials: true,
headers: {
'Content-Type': "application/json"
}
})
.post(url, json)
.then(response => {
method(response)
})
.catch(error => {
error_method(error)
});
break;
case "get":
await axios
.create({
xsrfHeaderName: 'X-CSRF-Token',
withCredentials: true,
headers: {
'Content-Type': "application/json"
}
})
.get(url)
.then(response => {
method(response)
})
.catch(error => {
error_method(error)
});
break;
}
}