Node.jsにおけるHTTPリクエストの処理について完全かつ包括的なガイドを提供します。Node.jsは、サーバーサイドのJavaScript環境として非常に人気があります。特に、HTTPリクエストを効率的に処理する能力は、その大きな強みの一つです。このガイドでは、Node.jsでHTTPリクエストをどのように処理するか、基本的な概念から応用的な使い方まで詳しく説明します。
1. Node.jsのHTTPモジュールとは?
Node.jsには標準で「http」というモジュールが含まれており、これを使うことで簡単にHTTPサーバーを作成し、リクエストに対応することができます。このモジュールを使用することで、リクエストの取得、レスポンスの送信、エラーハンドリングなどを行うことができます。

2. HTTPサーバーの作成
まず、最も基本的なHTTPサーバーの作成方法を紹介します。このサーバーは、指定されたポートでリクエストを待ち受け、受け取ったリクエストに対してレスポンスを返します。
javascriptconst http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello, World!');
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
このコードは、localhost:3000
で動作するシンプルなHTTPサーバーを作成します。http.createServer
メソッドはリクエストを受け取り、コールバック関数内でレスポンスを処理します。res.writeHead
でHTTPステータスコードとヘッダーを指定し、res.end
でレスポンスボディを送信します。
3. リクエストメソッドの処理
HTTPリクエストは通常、GET
やPOST
、PUT
、DELETE
などの異なるメソッドを持ちます。これらのメソッドに基づいて適切な処理を行うことができます。例えば、GET
リクエストに対してはデータを取得し、POST
リクエストには新しいデータを送信する処理を行います。
javascriptconst http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('GET Request Received');
} else if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(`POST Request Received with Body: ${body}`);
});
} else {
res.writeHead(405, {'Content-Type': 'text/plain'});
res.end('Method Not Allowed');
}
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
このサーバーでは、GET
リクエストを受けるとその旨を、POST
リクエストを受けると送信されたデータをレスポンスとして返します。それ以外のメソッドには「405 Method Not Allowed」のステータスコードを返します。
4. クエリパラメータの処理
HTTPリクエストには、URLにクエリパラメータを追加することができます。例えば、http://localhost:3000/?name=John
というURLがあった場合、name
というクエリパラメータがJohn
という値を持っています。これをNode.jsで処理するには、url
モジュールを使用します。
javascriptconst http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const name = parsedUrl.query.name;
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(`Hello, ${name ? name : 'Guest'}!`);
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
ここでは、url.parse
を使ってリクエストURLを解析し、クエリパラメータにアクセスしています。この例では、name
パラメータがあればそれを返し、なければ「Guest」と表示します。
5. リクエストヘッダーの処理
HTTPリクエストにはヘッダーが含まれています。これらのヘッダーを解析して、リクエストに含まれる情報を取得することができます。例えば、Content-Type
やUser-Agent
などのヘッダーを取得することができます。
javascriptconst http = require('http');
const server = http.createServer((req, res) => {
const userAgent = req.headers['user-agent'];
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(`Your User-Agent is: ${userAgent}`);
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
このコードでは、リクエストヘッダーからUser-Agent
を取得して、それをレスポンスとして返しています。
6. POSTデータの処理
POST
リクエストは、リクエストボディにデータを含むことができます。例えば、フォームから送信されたデータやJSONデータなどです。これらのデータを処理するには、リクエストのdata
イベントをリッスンし、最終的にend
イベントで全データを取得します。
javascriptconst http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(`Received data: ${body}`);
});
} else {
res.writeHead(405, {'Content-Type': 'text/plain'});
res.end('Only POST requests are accepted');
}
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
7. エラーハンドリング
HTTPサーバーでエラーハンドリングを行うことは非常に重要です。例えば、リクエストの処理中にエラーが発生した場合、適切なHTTPステータスコードを返す必要があります。
javascriptconst http = require('http');
const server = http.createServer((req, res) => {
try {
if (req.method === 'GET') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('GET Request');
} else {
throw new Error('Method Not Supported');
}
} catch (error) {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.end(`Internal Server Error: ${error.message}`);
}
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
このコードでは、try-catch
を使用してエラーをキャッチし、500 Internal Server Errorを返しています。
8. 外部ライブラリを使用したHTTPリクエストの処理
Node.jsの標準モジュール「http」を使用してリクエストを処理する方法は基本的なもので、より高度な機能を使いたい場合は外部ライブラリを使用することもあります。たとえば、express
というライブラリを使用すれば、より簡単にHTTPリクエストを処理することができます。
javascriptconst express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
express
を使うと、ルーティングやミドルウェアの利用、エラーハンドリングが非常に簡単になります。
まとめ
Node.jsを使用したHTTPリクエストの処理には、標準モジュールの「http」を使う方法が基本となりますが、より複雑なアプリケーションでは外部ライブラリを使用することが一般的です。リクエストメソッド、クエリパラメータ、リクエストヘッダー、POSTデータの処理方法を理解し、エラーハンドリングをしっかりと行うことが、効率的で安全なサーバーの構築に繋がります。