0
0

JavaScript HTTPリクエスト GET/POST

Last updated at Posted at 2024-08-15

GETリクエストを使い、テキストデータを取得する

JavaScriptを使い、HTTP通信によって、テキストデータを通信先から取得する。

GETコード

function fetchUserInfo() {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", "http://127.0.0.1:8080/page.html");
    xhr.send();
    xhr.responseType = "text";
    xhr.onload = () => {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr);
            const data = xhr.response;
            console.log(data);
        } else {
            console.log(`Error: ${xhr.status}`);
        }
    };
}

実行結果

image.png

※responseTypeを対応した値に指定しないとエラーが発生する。
 GETではなく、POSTになると実装が変わる。

POSTコード

function HttpPostRequest() {
    let txt_name = document.getElementById('name');
    let txt_age = document.getElementById('age');
    let txt_email = document.getElementById('email');

    const xhr = new XMLHttpRequest();
    xhr.open("POST", "http://127.0.0.1:8081/");
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    const body = JSON.stringify({
        name: txt_name.value,
        age: txt_age.value,
        email: txt_email.value,
    });
    xhr.onload = () => {
    if (xhr.readyState == 4 && xhr.status == 201) {
        console.log(JSON.parse(xhr.responseText));
    } else {
        console.log(`Error: ${xhr.status}`);
    }
    };
    xhr.send(body);
}

実行結果

image.png

C:\work\開発\test_javascript>py tcp_server.py
host:127.0.0.1 port:8081
Waiting for connection
Established connection
b'POST / HTTP/1.1\r\nHost: 127.0.0.1:8081\r\nConnection: keep-alive\r\nContent-Length: 40\r\nsec-ch-ua: "Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"\r\nContent-Type: application/x-www-form-urlencoded\r\nsec-ch-ua-mobile: ?0\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36\r\nsec-ch-ua-platform: "Windows"\r\nAccept: */*\r\nOrigin: http://127.0.0.1:8080\r\nSec-Fetch-Site: same-site\r\nSec-Fetch-Mode: cors\r\nSec-Fetch-Dest: empty\r\nReferer: http://127.0.0.1:8080/\r\nAccept-Encoding: gzip, deflate, br, zstd\r\nAccept-Language: ja,en-US;q=0.9,en;q=0.8\r\n\r\n{"name":"aaa","age":"bbb","email":"ccc"}'

送信/受信もできているが、サーバからクライアントに返信できていないようみ見える。

参考

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