プログラミングBlog

Node.jsでhttpメソッド① GETとPOST

HTTPメソッドとは?

クライアントからサーバーに対して送られる要求のこと。
HTTPメソッドでサーバーに何をしてほしいかを伝えることができる。

メソッドの種類

MDNによると全部で9種類。
developer.mozilla.org

今回は代表的な4つのメソッドについて調べました。
GET、POST、PUT、DELETEこれらの4つのメソッドで
データ操作するうえで基本となるCRUDの性質を満たしています。
まずは4つのメソッドを学んでいきましょう。

メソッド名 CRUD 説明
GET READ 読み込み
POST CREATE 作成
PUT UPDATE 更新
DELETE DELETE 削除

GETとPOSTのハンズオン

index.js

const http = require('http');
const fs = require('fs');

const hostname = "127.0.0.1";
const port = 3000;

const server = http.createServer(function (request, response) {
    fs.readFile('./index.html', 'utf-8', readIndex);
    function readIndex(error, data) {
        console.log(request.method);
        console.log(request.url);
        response.end(data);
    }
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form action="/" method="GET">
        <input name="get" value="getValue">
        <input type="submit" value="GET送信" />

    </form>
    <form action="/" method="POST">
        <input name="post" value="postValue">
        <input type="submit" value="POST送信" />
    </form>
</body>

</html>

inputボタンを押下時に、サーバー側に送られたRequestを 検証ツールとログに確認を行う。
HTMLのinputタグは、GETとPOSTのみサポートしているため、DELETEとPUTは別の方法を考えたい。