Node.js http モジュール
Node.js のhttpモジュールは Node.js の組み込みコアモジュールの 1 つであり、開発者が HTTP サーバーとクライアントを作成できるようにします。このモジュールを通じて、HTTP リクエストとレスポンスを簡単に処理し、Web アプリケーションや API サービスを構築できます。
httpこのモジュールは、サーバーの作成と HTTP リクエストの送信機能を提供し、Web アプリケーション構築の基盤となります。HTTP/1.1 プロトコルをサポートし、さまざまな HTTP 関連の操作を処理するための豊富な API を提供します。
HTTP サーバーの作成
使用httpモジュールでサーバーを作成するのは非常に簡単です。以下は最も基本的な例です:
サンプル
const http = require('http');
// HTTP サーバーを作成
const server = http.createServer((req, res) => {
// レスポンスヘッダーを設定
res.writeHead(200, {'Content-Type': 'text/plain'});
// レスポンスデータを送信
res.end('Hello, World!\n');
});
// 3000 番ポートを監視
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
// HTTP サーバーを作成
const server = http.createServer((req, res) => {
// レスポンスヘッダーを設定
res.writeHead(200, {'Content-Type': 'text/plain'});
// レスポンスデータを送信
res.end('Hello, World!\n');
});
// 3000 番ポートを監視
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
コード解析
require('http')- Node.js の http モジュールをインポートhttp.createServer()- HTTP サーバーのインスタンスを作成- コールバック関数
(req, res) => {...}- 各 HTTP リクエストを処理req- リクエストオブジェクト。クライアントから送信されたリクエスト情報を含むres- レスポンスオブジェクト。クライアントにレスポンスを送信するために使用
res.writeHead()- レスポンスヘッダーを設定res.end()- レスポンスを終了し、データを送信server.listen()- サーバーを起動して指定ポートを監視
HTTP リクエストの処理
HTTP サーバーはさまざまな種類のリクエストを処理できる必要があります。次に、リクエスト情報を解析する方法を見てみましょう:
サンプル
const http = require('http');
const server = http.createServer((req, res) => {
// リクエストメソッド、URL、リクエストヘッダーを取得
const { method, url, headers } = req;
// リクエスト情報を記録
console.log(`受信した ${method}リクエスト、パス: ${url}`);
console.log('リクエストヘッダー:', headers);
// リクエストメソッドに基づいて処理
if (method === 'GET') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('これは GET リクエストです\n');
} else if (method === 'POST') {
let body = '';
// POST データを収集
req.on('data', chunk => {
body += chunk;
});
// データの受信が完了
req.on('end', () => {
console.log('POST データ:, body);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('データを受信しました\n');
});
} else {
res.writeHead(405, {'Content-Type': 'text/plain'});
res.end('メソッドは許可されていません\n');
}
});
server.listen(3000);
const server = http.createServer((req, res) => {
// リクエストメソッド、URL、リクエストヘッダーを取得
const { method, url, headers } = req;
// リクエスト情報を記録
console.log(`受信した ${method}リクエスト、パス: ${url}`);
console.log('リクエストヘッダー:', headers);
// リクエストメソッドに基づいて処理
if (method === 'GET') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('これは GET リクエストです\n');
} else if (method === 'POST') {
let body = '';
// POST データを収集
req.on('data', chunk => {
body += chunk;
});
// データの受信が完了
req.on('end', () => {
console.log('POST データ:, body);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('データを受信しました\n');
});
} else {
res.writeHead(405, {'Content-Type': 'text/plain'});
res.end('メソッドは許可されていません\n');
}
});
server.listen(3000);
リクエストオブジェクト (req) の一般的なプロパティ
req.method: HTTP リクエストメソッド (GET, POST, PUT, DELETE など)req.url: リクエストの URL パスreq.headers: リクエストヘッダーオブジェクトreq.httpVersion: HTTP プロトコルバージョン
レスポンスオブジェクト (res) の一般的なメソッド
res.writeHead(statusCode, headers): レスポンスステータスコードとヘッダーを設定res.write(data): レスポンスボディを書き込むres.end([data]): レスポンスを終了し、必要に応じて最後のデータを送信するres.setHeader(name, value): レスポンスヘッダーを設定
HTTP リクエストの送信
httpモジュールはサーバーを作成できるだけでなく、クライアントとして HTTP リクエストを送信することもできます:
サンプル
const http = require('http');
// GET リクエストを送信
http.get('http://jsonplaceholder.typicode.com/posts/1', (res) => {
let data = '';
// データを受信
res.on('data', (chunk) => {
data += chunk;
});
// データの受信が完了
res.on('end', () => {
console.log('レスポンスデータ:, JSON.parse(data));
});
}).on('error', (err) => {
console.error('リクエストエラー:, err);
});
// GET リクエストを送信
http.get('http://jsonplaceholder.typicode.com/posts/1', (res) => {
let data = '';
// データを受信
res.on('data', (chunk) => {
data += chunk;
});
// データの受信が完了
res.on('end', () => {
console.log('レスポンスデータ:, JSON.parse(data));
});
}).on('error', (err) => {
console.error('リクエストエラー:, err);
});
POST リクエストの送信
サンプル
const http = require('http');
// リクエストオプション
const options = {
hostname: 'jsonplaceholder.typicode.com',
port: 80,
path: '/posts',
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
};
// リクエストを作成
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('レスポンス:, JSON.parse(data));
});
});
// エラーを処理
req.on('error', (err) => {
console.error('リクエストエラー:, err);
});
// リクエストデータを書き込む
const postData = JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
});
req.write(postData);
req.end();
// リクエストオプション
const options = {
hostname: 'jsonplaceholder.typicode.com',
port: 80,
path: '/posts',
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
};
// リクエストを作成
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('レスポンス:, JSON.parse(data));
});
});
// エラーを処理
req.on('error', (err) => {
console.error('リクエストエラー:, err);
});
// リクエストデータを書き込む
const postData = JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
});
req.write(postData);
req.end();
実際の適用シナリオ
1. RESTful API の作成
サンプル
const http = require('http');
const server = http.createServer((req, res) => {
const { method, url } = req;
// シンプルなルーティング処理
if (method === 'GET' && url === '/api/users') {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify([{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}]));
} else if (method === 'POST' && url === '/api/users') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
const newUser = JSON.parse(body);
// ここでデータベースに保存できる
res.writeHead(201, {'Content-Type': 'application/json'});
res.end(JSON.stringify({id: Date.now(), ...newUser}));
});
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not Found\n');
}
});
server.listen(3000);
const server = http.createServer((req, res) => {
const { method, url } = req;
// シンプルなルーティング処理
if (method === 'GET' && url === '/api/users') {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify([{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}]));
} else if (method === 'POST' && url === '/api/users') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
const newUser = JSON.parse(body);
// ここでデータベースに保存できる
res.writeHead(201, {'Content-Type': 'application/json'});
res.end(JSON.stringify({id: Date.now(), ...newUser}));
});
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not Found\n');
}
});
server.listen(3000);
2. プロキシサーバー
サンプル
const http = require('http');
const proxy = http.createServer((clientReq, clientRes) => {
// ターゲットサーバーにリクエストを送信
const options = {
hostname: 'example.com',
port: 80,
path: clientReq.url,
method: clientReq.method,
headers: clientReq.headers
};
const proxyReq = http.request(options, (proxyRes) => {
// ターゲットサーバーのレスポンスをクライアントに転送
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(clientRes);
});
// クライアントのリクエストボディを転送
clientReq.pipe(proxyReq);
});
proxy.listen(8080);
const proxy = http.createServer((clientReq, clientRes) => {
// ターゲットサーバーにリクエストを送信
const options = {
hostname: 'example.com',
port: 80,
path: clientReq.url,
method: clientReq.method,
headers: clientReq.headers
};
const proxyReq = http.request(options, (proxyRes) => {
// ターゲットサーバーのレスポンスをクライアントに転送
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(clientRes);
});
// クライアントのリクエストボディを転送
clientReq.pipe(proxyReq);
});
proxy.listen(8080);
ベストプラクティス
- エラー処理:リクエストとレスポンスのエラーイベントを常に処理する
- 性能の考慮:高並行アプリケーションの場合は、コネクションプールの使用を検討する
- セキュリティ:
- すべての入力を検証する
- 適切なセキュリティヘッダーを設定する
- リクエストボディのサイズを制限して DOS 攻撃を防ぐ
- ストリームを使用する:大きなファイルの転送には、ストリーム処理を使用する
- フレームワークを検討する:複雑なアプリケーションには、Express、Koa などのフレームワークの使用を検討する
まとめ
Node.js のhttpモジュールは、ネットワークアプリケーションを構築するための基礎的な能力を提供します。現在では多くの高度なフレームワークが利用可能ですが、理解することはhttpモジュールの動作原理は、すべての Node.js 開発者にとって極めて重要です。このコアモジュールを習得することで、Web アプリケーションの動作メカニズムをより深く理解し、要件に応じてカスタマイズされたソリューションを構築することができます。
Node.js 組み込みモジュール