< 前の記事
パッケージの管理
[Node.js]簡易Webサーバーの実装
公開日:2026-02-03
更新日:2026-02-03
更新日:2026-02-03
1. 概要
fetch などに応答するためのテスト用簡易Webサーバーを実装します。
Node.js の HTTP と言う組み込みモジュールを使用します。
Express は使用しません。
Node.js の HTTP と言う組み込みモジュールを使用します。
Express は使用しません。
2. 簡易 Web サーバーの実装と起動
2.1 package.json の作成
package.json を作成して、その中の type を module にします。
type を module にすると ES Modules(ESM)として実行されるようになります(import が使えるようになる)。
ちなみに、commonjs のままでも、JavaScript の拡張子を .mjs にすると、ES Modules として扱われます。
コマンド
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 が実行できる環境で次のコマンドを実行します。
http://localhost:3000/ にアクセスして、Hello と表示されれば OK です。
Node.js が実行できる環境で次のコマンドを実行します。
コマンド
node server.js
http://localhost:3000/ にアクセスして、Hello と表示されれば OK です。
3. テスト用コード
index.html
ブラウザで index.html にアクセスすると、
http://localhost:3000/articles からデータを取得してコンソールに出力します。
コード
<!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 からデータを取得してコンソールに出力します。
< 前の記事
パッケージの管理

