LoginSignup
5
3

More than 5 years have passed since last update.

1分でajaxのお試し環境を作る with Docker & nginx

Posted at

昨日の業務の際、急遽APIをajaxで実行するテストが必要になりました。
CORSの確認だったので、webサーバーを立てた方が良いはずなのですが、
サーバーの用意とajax通信するソースの用意が面倒そうだと感じました:kissing:

けれど、webで調べたサンプルを組み合わせることで、
簡単にajaxをお試しできる環境ができました。
また、いつか使うと思うのでメモメモ :pencil:

作業ディレクトリとhtmlの作成

$ mkdir test
$ vim test/index.html

index.htmlには以下を貼り付けてください
(ajaxの通信先は適宜変更してください)

<!DOCTYPE html>

<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>
    ajaxテスト
  </title>
</head>
<body>
  <p>
    ajaxテスト
  </p>
  <input id="button" type="button" value="テスト">

  <script>
    var url = "https://api.github.com/search/repositories?q=javascript";
    var xhr = new XMLHttpRequest();

    document.getElementById("button").onclick = function() {

      xhr.open('GET', url);
      xhr.send();

      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {

          console.log(JSON.parse(xhr.responseText));

        }
      }
    };
  </script>
</body>
</html>

dockerでnginxを立て、起動

docker run --name sample1 -p 8090:80 -v $PWD/test:/usr/share/nginx/html -d nginx

テスト

http://localhost:8090/ にアクセスして、consoleを開きましょう。
テストボタンを押下して、APIの実行結果がconsoleに表示できれば完了です。

test.jpg

お疲れさまでした :airplane:

参考

5
3
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
5
3