0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[初心者用] Node.jsでHTTPサーバーを作ってみよう

Posted at

形あるものを作成してアウトプットしよう

現在の知識

①Node.jsの基礎知識

②npmの基礎知識

経緯

ChatGPTに、現在の知識だけで作れるサーバーを教えてもらったので、写経をしていく

写経をする

server.js
const http = require('http');

const server = http.createServer((req, res) => {
  res.writeHead(200, {"content-type":"text/plain"});
  res.end('hell node.js!!!!!!!!!!!!');
});

server.listen(3000, () => {
  console.log("Server is running on http://localhost:3000")
});
node server.js

2025-10-26 0.39の画像.jpeg

①モジュールの読み込み(HTTPサーバーの準備)

server.js
// repuire → CJSのimportの方法
const http = require('http');

②サーバーオブジェクトの作成(リクエストをどう返すか?)

server.js
// http.createServer → HTTPサーバーを作れる
// 引数にはreqとresを渡す
const server = http.createServer((req, res) => {

req
Request → ブラウザから来る情報

res
Response → サーバーが返す情報


疑問① 今回のコードでは req を使っていないけど設定するの?

結論
使っていなくても設定するのが普通

理由
http.createServerのコールバック関数は第一引数(req)と第二引数(res)という決まった形に基づいている。今回が簡単なコードのため使わなかっただけ


レスポンスヘッダーの設定

server.js
// res.writeHead → HTTPレスポンスのヘッダーを設定するメソッド
// 200 → ステータスコード
// "content-type":"text/plain" → 返すテキストがプレーンコード
res.writeHead(200, {"content-type":"text/plain"});

疑問② ステータスコードとは?

サーバーがクライアント(ブラウザ)に対して返す「結果の種類」を示す数字

2025-10-26 2.16の画像.jpeg

このコードを見て「成功か失敗か」を判断する
Node.jsやExpressが自動でつけてくれる


疑問③ その他のContent-Type

2025-10-26 2.20の画像.jpeg


レスポンスの本体を送信して終了

server.js
// res.end → クライアントへレスポンスを送り、その処理を終了するメソッド
res.end('hell node.js!!!!!!!!!!!!');

ポート3000でサーバーを待ち受ける

server.js
// server.listen(3000) → ポート3000でリクエストを受け付けるようにする
server.listen(3000, () => {
  // コールバック関数のconsole.log()はサーバーの起動が成功したら1回だけ実行される
  console.log("Server is running on http://localhost:3000")
});
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?