Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

昨日の業務の際、急遽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:

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした