【決定版】Node.js で HTTP リダイレクトをスマートに処理する 3 つの方法とサンプルコード
Node.js で HTTP リダイレクトを処理する方法
res.writeHead() と res.end() を使用する
最も基本的な方法は、res.writeHead()
と res.end()
関数を使用して、ステータスコードと Location ヘッダーを設定する方法です。
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/old/path') {
res.writeHead(302, { 'Location': '/new/path' });
res.end();
} else {
// その他の処理
}
});
server.listen(3000);
この例では、/old/path
にアクセスすると、ステータスコード 302 (Found) と Location ヘッダーに /new/path
を設定し、クライアントを新しい URL にリダイレクトします。
http.get()
関数を使用して、リダイレクトを処理する方法もあります。
const http = require('http');
const options = {
hostname: 'example.com',
port: 80,
path: '/old/path',
};
http.get(options, (res) => {
if (res.statusCode === 302) {
const location = res.headers.location;
console.log(`Redirect to: ${location}`);
// 新しい URL に再帰的にリクエストを送信
http.get(location, (newRes) => {
// 新しいレスポンスを処理
});
} else {
// その他の処理
}
});
この例では、/old/path
に対する GET リクエストを行い、レスポンスのステータスコードが 302 (Found) であるかどうかを確認します。ステータスコードが 302 の場合、Location ヘッダーの値を取得して新しい URL に再帰的に GET リクエストを送信します。
補足
- リダイレクトの種類には、301 (Moved Permanently) や 307 (Temporary Redirect) などがあります。使用するステータスコードは、状況に応じて適切なものを選択する必要があります。
- Location ヘッダーには、絶対 URL だけでなく、相対 URL を指定することもできます。
- 一部のライブラリ (例: Express) は、上記で説明したよりも簡単にリダイレクトを処理できる機能を提供しています。
Node.js での HTTP リダイレクト処理のサンプルコード
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/old/path') {
res.writeHead(302, { 'Location': '/new/path' });
res.end();
} else if (req.url === '/new/path') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('This is the new path.');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found.');
}
});
server.listen(3000);
このコードでは、以下の処理が行われます。
- HTTP サーバーを作成します。
- リクエストハンドラー関数を定義します。
/new/path
にアクセスされた場合、ステータスコード 200 (OK) と Content-Type ヘッダーにtext/plain
を設定し、"This is the new path." というメッセージをレスポンスとして返します。
http.get() を使用する
const http = require('http');
const options = {
hostname: 'example.com',
port: 80,
path: '/old/path',
};
http.get(options, (res) => {
if (res.statusCode === 302) {
const location = res.headers.location;
console.log(`Redirect to: ${location}`);
// 新しい URL に再帰的にリクエストを送信
const newOptions = {
hostname: url.parse(location).hostname,
port: url.parse(location).port,
path: url.parse(location).path,
};
http.get(newOptions, (newRes) => {
console.log(`New response status code: ${newRes.statusCode}`);
// 新しいレスポンスを処理
});
} else {
console.log(`Response status code: ${res.statusCode}`);
// その他の処理
}
});
http.get()
関数を使用して、example.com
の/old/path
に対する GET リクエストを送信します。- レスポンスのステータスコードが 302 (Found) であるかどうかを確認します。
- ステータスコードが 302 の場合、Location ヘッダーの値を取得して新しい URL に再帰的に GET リクエストを送信します。
- 新しいレスポンスのステータスコードをコンソールに出力します。
- その他の処理を行います。
- 上記のコードはあくまで一例であり、状況に応じて変更する必要があります。
- エラー処理やセキュリティ対策は、ご自身の責任で行ってください。
Node.js で HTTP リダイレクトを処理するその他の方法
Express フレームワークを使用する
Express は、Node.js で最も人気のある Web フレームワークの 1 つであり、HTTP リダイレクトを処理するための便利な機能を提供しています。
const express = require('express');
const app = express();
app.get('/old/path', (req, res) => {
res.redirect('/new/path');
});
app.get('/new/path', (req, res) => {
res.send('This is the new path.');
});
app.listen(3000);
このコードは、Express を使用して上記と同じリダイレクトを実装する方法を示しています。 res.redirect()
関数は、ステータスコード 302 (Found) と Location ヘッダーを自動的に設定します。
その他のライブラリを使用する
Express以外にも、HTTP リダイレクトを処理するためのライブラリはいくつかあります。
これらのライブラリは、それぞれ異なる機能と API を提供しています。
カスタムミドルウェアを作成する
高度な制御が必要な場合は、カスタムミドルウェアを作成してリダイレクトを処理することができます。
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/old/path') {
res.writeHead(302, { 'Location': '/new/path' });
res.end();
} else if (req.url === '/new/path') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('This is the new path.');
} else {
next();
}
});
server.use((req, res, next) => {
if (req.statusCode === 404) {
res.redirect('/');
}
});
server.listen(3000);
このコードでは、/old/path
にアクセスされた場合にリダイレクトを行うミドルウェアと、404 Not Found
エラーが発生した場合に /
にリダイレクトを行うミドルウェアを作成しています。
- シンプルなリダイレクトの場合は、
res.writeHead()
とres.end()
関数を使用するのが最も簡単です。 - Express を使用している場合は、
res.redirect()
関を使用すると便利です。
node.js http-redirect