0
0
お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

サーバーが機能しているかを確認するもの(?)をjsとhtmlで書く

Posted at

初めに

今回はサーバーが稼働しているかを確認するもの(※)をhtmlとjsで書きます
※...サーバからの応答があれば全部200で返します

ファイル構成

今回はhtmlファイル一つで大丈夫です

コードをコピペ

main.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>サーバーチェッカー</title>
</head>
<body>
    <center>
        <h2>テスト</h2>
        <input type="text" id="url" placeholder="URLを入力してください">
        <button onclick="checkServer()">チェック</button>
        <p id="status"></p>
        <iframe id="checkFrame" style="display:none;"></iframe>
        <p>※このコードはサーバが存在しているか確認しているだけなので、サーバが落ちていてもサーバからの応答があれば全部200で返します(CORSなどは例外)</p>
    </center>
    <script>
        function checkServer() {
            const urlInput = document.getElementById('url').value;
            const statusElement = document.getElementById('status');
            const iframe = document.getElementById('checkFrame');

            if (!urlInput) {
                alert('Error: URLが入力されていません');
                return;
            }

            iframe.onload = function() {
                statusElement.textContent = '指定したURLのステータス: 200 OK';
            };

            iframe.onerror = function() {
                statusElement.textContent = '指定したURLのステータス: URLが見つかりません';
            };

            iframe.src = urlInput;
        }
    </script>
</body>
</html>

仕組み

iframeを使って読み込みに成功したら200,エラーが発生したらエラーを返します

最後に

皆さんいかがだったでしょうか?今回はhtmlとjsを使ってサーバが機能しているかをチェックするプログラムを書いてみました。
それではまたお会いしましょう!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0