test.html 1.44 KB
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
    crossorigin="anonymous"></script>
</head>

<body>

</body>
<script>
  const tokenUrl = 'https://www.nifs-k.ac.jp/rmap/getToken.php';
  let rmToken = JSON.parse(localStorage.getItem('rmToken'));

  // トークン未取得 or 有効期限切れ
  if (!rmToken) {
    getToken();
  } else {
    const expDate = new Date(rmToken.exp);
    const now = new Date();
    if (expDate > now) {
      getToken();
    } else {
      console.log(rmToken);
    }
  }

  function getToken() {
    $.ajax({
      type: 'GET',
      url: tokenUrl,
      dataType: 'json',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        // 'Accept': 'application/ld+json,application/json;q=0.1',
        // 'Accept-Encoding': 'gzip',
        'Content-Type': 'application/json;'
      },
      success: function (data) {
        const now = new Date();
        const exp = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes() + 55);
        rmToken = {
          token: data.access_token,
          exp: exp
        };
        localStorage.setItem('rmToken', JSON.stringify(rmToken));
        console.log(rmToken);
      }
    });
  }

</script>

</html>