Node.jsでHTTPリクエストのクエリパラメータとボディデータを処理する

Node.jsのネイティブHTTPモジュールを用いて、クライアントからのGETおよびPOSTリクエストを正しく解析し、パラメータを抽出する方法について解説します。本実装では、組み込みモジュールのみを使用し、外部依存を排除します。

GETリクエストのクエリ文字列解析

GETリクエストのクエリパラメータはURLの?<query>部分に含まれます。`url`モジュールのparse()関数にtrueを第2引数として渡すことで、自動的にqueryプロパティにオブジェクト形式でパースされます。

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

const server = http.createServer((req, res) => {
  if (req.method === 'GET') {
    const parsedUrl = url.parse(req.url, true);
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ method: 'GET', params: parsedUrl.query }));
  }
});

POSTリクエストのボディ受信とデコード

POSTリクエストのボディはストリームとして送信されるため、dataイベントでチャンク単位で受信し、endイベントで受信完了を検知します。文字列化の際にはBuffer.toString()を明示的に使用し、エンコーディングの不整合を防ぎます。

const http = require('http');

const server = http.createServer((req, res) => {
  let body = '';

  if (req.method === 'POST') {
    req.on('data', (chunk) => {
      body += chunk.toString();
    });

    req.on('end', () => {
      try {
        const parsedBody = JSON.parse(body);
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ 
          method: 'POST', 
          received: parsedBody,
          timestamp: new Date().toISOString()
        }));
      } catch (e) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: 'Invalid JSON payload' }));
      }
    });
  }
});

統合サーバー:GETとPOSTを同時に処理

以下の実装では、リクエストメソッドに応じて分岐し、それぞれの処理ロジックを適用します。また、ヘッダーのContent-Typeを適切に設定し、クライアントとの互換性を確保しています。

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

const handler = (req, res) => {
  const headers = {
    'Content-Type': 'application/json; charset=utf-8',
    'Access-Control-Allow-Origin': '*'
  };

  if (req.method === 'GET') {
    const { query } = url.parse(req.url, true);
    res.writeHead(200, headers);
    res.end(JSON.stringify({ status: 'success', method: 'GET', query }));
  } 
  else if (req.method === 'POST') {
    let raw = '';
    req.on('data', chunk => raw += chunk.toString());
    req.on('end', () => {
      res.writeHead(201, headers);
      res.end(JSON.stringify({
        status: 'created',
        method: 'POST',
        payload: raw ? JSON.parse(raw) : null,
        length: Buffer.byteLength(raw)
      }));
    });
  } 
  else {
    res.writeHead(405, headers);
    res.end(JSON.stringify({ error: 'Method not allowed' }));
  }
};

const server = http.createServer(handler);
server.listen(3000, () => {
  console.log('HTTP server running on http://localhost:3000');
});

タグ: nodejs HTTP querystring url Stream

8月6日 23:00 投稿