Axios.jsでajaxするコードGETもPOSTも可能

提供:sufeeWiki
ナビゲーションに移動 検索に移動

概要

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;
  }
}

呼び出し方

const URL = " URL "
const JSON_DATA = {
hoge:"hogehoge"
}
const METHOD = response => {
  if(response.data.hoge !== undefined){
    console.log(response.data.hoge);
  }
}
const ERROR = error => {
  console.error(error);
}
ajax(URL , JSON_DATA , METHOD, ERROR, "post"); //post or get