4.

Node.js 最小サーバー構築 完全ガイド(http モジュール / Express / nodemon / ポート / トラブル対処)

編集
この記事の要点
  • Node.js は標準モジュール http だけで数行で HTTP サーバが書ける
  • server.jshttp.createServer().listen(port) を書き、node server.js で起動
  • リクエストハンドラ (req, res) => { ... } でレスポンスを組み立て、res.end() で送信
  • 本格的には Express 等のフレームワークを使うのが定番(ルーティング / ミドルウェア / エラー処理)
  • 開発時は nodemon でファイル保存時に自動再起動できると効率的

はじめに

Node.js は JavaScript でサーバサイド処理を書ける実行環境です。標準モジュールの http だけで、ブラウザからアクセスできる最小限の Web サーバが組めるため、入門にぴったりの題材です。

事前準備

  1. Node.js(推奨は LTS バージョン)をインストール
  2. 動作確認: ターミナルで node -v
  3. 適当な作業フォルダを作って移動
# Node.js のバージョン確認
node -v
# v20.10.0 などが表示されればOK

# 作業フォルダ作成
mkdir my-server
cd my-server

最小サーバー(http モジュール)

作業フォルダ内に server.js を作成し、以下を貼り付けます。

const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
    res.write('Node.js Server Start!');
    res.end();
});

server.listen(8000, () => {
    console.log('サーバー起動中... http://localhost:8000/');
});

起動

node server.js
# サーバー起動中... http://localhost:8000/

ブラウザで http://localhost:8000/ にアクセスすると Node.js Server Start! と表示されます。停止は Ctrl + C

HTML を返す

const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.end(`
        <!DOCTYPE html>
        <html lang="ja">
        <head><meta charset="UTF-8"><title>My Server</title></head>
        <body>
            <h1>こんにちは、Node.js</h1>
            <p>現在時刻: ${new Date().toLocaleString('ja-JP')}</p>
        </body>
        </html>
    `);
});

server.listen(8000);

JSON API を返す

const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
    res.end(JSON.stringify({
        message: 'Hello',
        time: new Date().toISOString()
    }));
});

server.listen(8000);

URL でルーティング

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

const server = http.createServer((req, res) => {
    const path = url.parse(req.url).pathname;

    if (path === '/') {
        res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
        res.end('トップページ');
    } else if (path === '/about') {
        res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
        res.end('Aboutページ');
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
        res.end('404 Not Found');
    }
});

server.listen(8000);

Express を使うと簡単

本格的にルーティングやミドルウェアを使うなら Express が定番です。

# npm 初期化
npm init -y

# Express インストール
npm install express
// app.js
const express = require('express');
const app = express();

app.get('/', (req, res) => {
    res.send('トップページ');
});

app.get('/about', (req, res) => {
    res.send('Aboutページ');
});

app.get('/api/users/:id', (req, res) => {
    res.json({ id: req.params.id, name: 'Taro' });
});

app.listen(8000, () => {
    console.log('Express server started: http://localhost:8000/');
});
node app.js

nodemon — 自動再起動

ファイル保存時にサーバを自動再起動してくれる開発ツール。手動で node server.js を打ち直す必要がなくなります。

# グローバルインストール
npm install -g nodemon

# 起動(node の代わりに nodemon)
nodemon server.js

ポート番号の選び方

範囲用途
0-1023well-known ports(管理者権限必要、80 / 443 等)
1024-49151registered ports(一般用、開発に使いやすい)
49152-65535dynamic / private ports(OS が動的に割当)

開発では 3000 / 4000 / 5000 / 8000 / 8080 がよく使われます。本番で 80 / 443 を使うときはリバースプロキシ(nginx 等)の後ろに置くのが一般的です。

環境変数でポート切替

const PORT = process.env.PORT || 8000;
server.listen(PORT, () => {
    console.log(`http://localhost:${PORT}/`);
});
# Linux / macOS
PORT=4000 node server.js

# Windows (PowerShell)
$env:PORT = 4000; node server.js

よくあるトラブル

症状原因 / 対処
EADDRINUSEポートが他のプロセスで使用中。別ポートに変えるか、占有プロセスを終了
EACCES1024 未満のポートに非 root で listen している。1024 以上に変更
文字化けContent-Type に charset=utf-8 を付ける
Cannot find module 'express'npm install express を実行
外部からつながらないOS / クラウドのファイアウォール、0.0.0.0 へバインドの確認

外部公開する際のポイント

  • 本番では Node を直接公開しない — nginx 等のリバースプロキシ越しが定番
  • HTTPS は Let's Encrypt + リバースプロキシで終端
  • プロセス管理には PM2、systemd、Docker 等
  • 環境変数で秘匿情報を管理(dotenv が便利)

FAQ

Q: 何度実行しても同じ画面しか出ない
A: ブラウザのキャッシュです。Ctrl + F5 で強制リロードを試してください。

Q: ポートを変えるには?
A: server.listen(3000) のように数値を変えて再起動するか、上記の環境変数方式を使います。

Q: TypeScript で書きたい
A: ts-nodetsx を使うとビルドなしで実行できます。本格運用なら tsc で JS にコンパイル → node dist/server.js

関連

  • Node.js — サーバサイド JS ランタイム
  • Express — 最も普及している Node 用 Web フレームワーク
  • npm — Node のパッケージマネージャ
  • nodemon — ファイル変更で自動再起動
  • http モジュール — Node 標準の HTTP サーバ機能
編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. インストール方法(Windows編)
  2. インストール方法(CentOS編)
  3. クイックスタート
  4. 簡単なサーバー構築と起動方法
  5. ExpressとEJSを使用した簡単なアプリの作成

最近更新/作成されたページ