9cubed
ブログ | PHP | JavaScript | TypeScript | Vue.js | Laravel | Tailwind | Vite | Python | MariaDB | SQLite | Node.js | Linux | PowerShell | Docker | Git | Web | その他
< 前の記事

パッケージの管理

Node.js

[Node.js]簡易Webサーバーの実装

公開日:2026-02-03
更新日:2026-02-03

1. 概要

fetch などに応答するためのテスト用簡易Webサーバーを実装します。
Node.js の HTTP と言う組み込みモジュールを使用します。
Express は使用しません。

2. 簡易 Web サーバーの実装と起動

2.1 package.json の作成

package.json を作成して、その中の type を module にします。
コマンド
npm init -y
npm pkg set type=module   # type を module にする

type を module にすると ES Modules(ESM)として実行されるようになります(import が使えるようになる)。
ちなみに、commonjs のままでも、JavaScript の拡張子を .mjs にすると、ES Modules として扱われます。

2.2 簡易 Web サーバーの実装

server.js
コード
import http from 'node:http';

const PORT = 3000;

const server = http.createServer((req, res) => {
  console.log(`[${req.method}] ${req.url}`);
  
  // CORS 対応
  res.setHeader('Access-Control-Allow-Origin', '*');  // 全て許可(本番環境ではNG)
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  
  // プリフライトリクエスト対応
  if (req.method === 'OPTIONS') {
    console.log('プリフライトリクエスト');
    res.writeHead(204);
    res.end();
    return;
  }
  
  if (req.method !== 'GET') {
    // GET 以外はエラー
    res.writeHead(405, { 'Content-Type': 'text/plain' });
    res.end('Method Not Allowed\n');
    return;
  }
  
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.end('Hello\n');
    return;
  }
  
  if (req.url === '/articles') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({
      message: 'success',
      articles: [
        { id: 1, title: 'Test1' },
        { id: 2, title: 'Test2' },
        { id: 3, title: 'Test3' },
      ]
    }, null, 2));
    return;
  }
  
  res.writeHead(404, { 'Content-Type': 'text/plain' });
  res.end('Not Found\n');
});

server.listen(PORT, () => {
  console.log(`http://localhost:${PORT}`);
});

2.3 簡易 Web サーバーの起動

簡易 Web サーバーを起動するには、
Node.js が実行できる環境で次のコマンドを実行します。
コマンド
node server.js

http://localhost:3000/ にアクセスして、Hello と表示されれば OK です。

3. テスト用コード

index.html
コード
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
    <script>
(async () => {
  try {
    const response = await fetch('http://localhost:3000/articles');
    
    if (!response.ok) {
      throw new Error(`Error:${response.status}`);
    }
    
    const data = await response.json();
    console.log("取得したデータ:", data);
  } catch (error) {
    console.error(error.message);
  }
})();
    </script>
</head>
<body>
TEST
</body>
</html>

ブラウザで index.html にアクセスすると、
http://localhost:3000/articles からデータを取得してコンソールに出力します。
< 前の記事

パッケージの管理

YouTube X

新着一覧

  • async、awaitJavaScript
  • Promise についてJavaScript
  • パッケージの管理Node.js
  • v-model(双方向バインディング)Vue.js
  • VS Code で GitHub を使ったソース管理Git
  • computed(再計算)Vue.js
  • watchDebounced(値の監視)Vue.js
  • watch(値の監視)Vue.js
  • change イベントVue.js
  • v-memoVue.js

アーカイブ

  • 2026/03
  • 2026/02
  • 2026/01
  • 2025/12
  • 2025/11
  • 2025/10
  • 2025/09
  • 2025/08
  • /00

以前のカテゴリー一覧

  • CakePHP3
  • CentOS7
  • HTML・CSS・JavaScript
  • Haskell
  • JavaScript
  • Kotlin
  • Laravel5
  • PHP
  • Python
  • Ruby
  • RubyOnRails5
  • TypeScript
  • Vue.js
  • Webサーバ講座
  • Webプログラミング講座
  • jQuery
  • linux
  • パソコン講座
  • ブログ
  • プログラミング講座
  • メモ帳作成講座
  • 数学

Copyright © 9cubed. All Rights Reserved.

プライバシーポリシー 利用規約
▲