LoginSignup
0
0

Node.jsによるHTTPサーバの基本

Posted at

完成系

main.js
"use strict";

const http = require("http");
const port = 3000;

const server = http.createServer((request, response) => {
    response.writeHead(200, {
      "Content-Type": "text/html"
    });

    const responseMessage = "<h1>Hello World!</h1>";
    response.write(responseMessage);
    response.end();
    console.log(`Sent a response : ${responseMessage}`);
});

server.listen(port);
console.log(`The server has started and is listening on port number: ${port}`);
console.log(`URL:http://localhost:3000/`);

各行の説明

"use strict";
一行目に書くことで、未定義の変数の使用を禁止する

const http = require("http");
httpモジュールの読み込み

const port = 3000;
ポート番号を3000番に設定

const server = http.createServer((request, response) => {});
httpサーバの構築にcreateServer()メソッドを使用
第1引数 request:クライアントからのリクエストに関する機能を提供するオブジェクト
第2引数 response:クラアントへのレスポンスに関する機能を提供するオブジェクト
createServer()メソッド内の処理はhttpリクエストを受け取った際に実行される

response.writeHead(200, {"Content-Type": "text/html"});
ステータス情報(第一引数)と、ヘッダ情報(第二引数)の書き出し
※Content-Typeの一覧
https://qiita.com/AkihiroTakamura/items/b93fbe511465f52bffaa

const responseMessage = "<h1>Hello World!</h1>";
コンテンツ(表示させる内容)を指定

response.write(responseMessage);
コンテンツの書き出し

response.end();
コンテンツの完了

console.log(`Sent a response : ${responseMessage}`);
コンテンツの中身をログで出力

server.listen(port);
ポートを待機状態にする
ポートが待機状態でない場合通信できない

console.log(`The server has started and is listening on port number: ${port}`);
ポート番号を格納した定数の中身をログで出力

console.log(`URL:http://localhost:3000/`);
構築したHTTPサーバにHTTPリクエストを送るためのURLをログで出力

実行方法

$ node main.js

コンソールに出力されたURL(http://localhost:3000/) にブラウザでアクセス
ブラウザ上に Hello World! が出力される

URLの説明

http:
通信方式 (プロトコル) を指定

//localhost
リクエスト先のサーバの住所となるIPアドレス、もしくはドメイン名を指定
localhostをIPアドレスに直すと127.0.0.1で、自身のPCを示している

:3000
アクセス先のポート番号を指定

/
サーバのどのディレクトリ (パス) にアクセスするかを指定

参考:

Node.jsのスクリプトの基本を覚えよう (2/5)
https://www.tuyano.com/index3?id=1126003&page=2
Node.jsでHTTPサーバを構築しよう
https://zenn.dev/wkb/books/node-tutorial/viewer/todo_02

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