Node.js url モジュール
Node.jsのurlモジュールは組み込みモジュールであり、URL(統一リソースロケータ)の処理と解析に使用されます。URL文字列を簡単に解析、フォーマット、処理するための一連の実用的なメソッドを提供します。
URL(Uniform Resource Locator)は、インターネット上でリソースを識別して位置を特定するためのアドレスです。例:
https://www.example.com:8080/path/to/resource?query=string#hash
コアメソッド
url.parse() メソッド
url.parse()このメソッドは、URL文字列をURLオブジェクトに解析するために使用されます。
例
const url = require('url');
const urlString = 'https://www.example.com:8080/path/to/resource?query=string#hash';
const parsedUrl = url.parse(urlString);
console.log(parsedUrl);
const urlString = 'https://www.example.com:8080/path/to/resource?query=string#hash';
const parsedUrl = url.parse(urlString);
console.log(parsedUrl);
出力結果には以下のプロパティが含まれます:
protocol: プロトコル(例:'https:')host: ホスト名とポート(例:'www.example.com:8080')hostname: ホスト名(例:'www.example.com')port: ポート番号(例:'8080')pathname: パス部分(例:'/path/to/resource')query: クエリ文字列(例:'query=string')hash: フラグメント識別子(例:'#hash')
url.format() メソッド
url.format()メソッドとparse()反対に、URLオブジェクトを文字列形式に変換します。
例
const url = require('url');
const urlObject = {
protocol: 'https:',
host: 'www.example.com:8080',
pathname: '/path/to/resource',
query: { query: 'string' },
hash: '#hash'
};
const formattedUrl = url.format(urlObject);
console.log(formattedUrl);
// 出力: https://www.example.com:8080/path/to/resource?query=string#hash
const urlObject = {
protocol: 'https:',
host: 'www.example.com:8080',
pathname: '/path/to/resource',
query: { query: 'string' },
hash: '#hash'
};
const formattedUrl = url.format(urlObject);
console.log(formattedUrl);
// 出力: https://www.example.com:8080/path/to/resource?query=string#hash
url.resolve() メソッド
url.resolve()このメソッドは、ベースURLに対する相対的なターゲットURLを解析するために使用されます。
例
const url = require('url');
const baseUrl = 'https://www.example.com/path/';
const relativeUrl = 'to/resource';
const resolvedUrl = url.resolve(baseUrl, relativeUrl);
console.log(resolvedUrl);
// 出力: https://www.example.com/path/to/resource
const baseUrl = 'https://www.example.com/path/';
const relativeUrl = 'to/resource';
const resolvedUrl = url.resolve(baseUrl, relativeUrl);
console.log(resolvedUrl);
// 出力: https://www.example.com/path/to/resource
URL オブジェクトの構造
完全なURLオブジェクトには通常、以下のプロパティが含まれます:
- プロトコル (protocol)- 例:'http:' または 'https:'
- 認証情報 (auth)- ユーザー名とパスワードを含む
- ホスト (host)- ホスト名とポート番号
- ホスト名 (hostname)- ホスト名のみ
- ポート (port)- ポート番号
- パス (pathname)- リソースパス
- クエリ文字列 (search)- '?' で始まるクエリ文字列
- クエリパラメータ (query)- クエリ文字列の解析結果
- フラグメント識別子 (hash)- '#' で始まるフラグメント識別子
新版 URL API
Node.jsには、WHATWG URL標準に基づく新しいAPIも用意されています:
URL クラス
例
const { URL } = require('url');
const myUrl = new URL('https://www.example.com:8080/path/to/resource?query=string#hash');
console.log(myUrl.protocol); // 'https:'
console.log(myUrl.hostname); // 'www.example.com'
console.log(myUrl.port); // '8080'
console.log(myUrl.pathname); // '/path/to/resource'
console.log(myUrl.search); // '?query=string'
console.log(myUrl.hash); // '#hash'
const myUrl = new URL('https://www.example.com:8080/path/to/resource?query=string#hash');
console.log(myUrl.protocol); // 'https:'
console.log(myUrl.hostname); // 'www.example.com'
console.log(myUrl.port); // '8080'
console.log(myUrl.pathname); // '/path/to/resource'
console.log(myUrl.search); // '?query=string'
console.log(myUrl.hash); // '#hash'
URLSearchParams クラス
URLSearchParamsクエリ文字列を処理するための便利なメソッドを提供します:
例
const { URL, URLSearchParams } = require('url');
const myUrl = new URL('https://example.com/?name=John&age=30');
const params = new URLSearchParams(myUrl.search);
// パラメータを取得する
console.log(params.get('name')); // 'John'
console.log(params.get('age')); // '30'
// パラメータを追加する
params.append('city', 'New York');
// パラメータを削除する
params.delete('age');
// 文字列に変換する
console.log(params.toString()); // 'name=John&city=New+York'
const myUrl = new URL('https://example.com/?name=John&age=30');
const params = new URLSearchParams(myUrl.search);
// パラメータを取得する
console.log(params.get('name')); // 'John'
console.log(params.get('age')); // '30'
// パラメータを追加する
params.append('city', 'New York');
// パラメータを削除する
params.delete('age');
// 文字列に変換する
console.log(params.toString()); // 'name=John&city=New+York'
実際のユースケース
1. リクエストURLを解析する
HTTPサーバーでクライアントのリクエストURLを解析します:
例
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
console.log('Path:', parsedUrl.pathname);
console.log('Query:', parsedUrl.query);
res.end('URL parsed successfully');
});
server.listen(3000);
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
console.log('Path:', parsedUrl.pathname);
console.log('Query:', parsedUrl.query);
res.end('URL parsed successfully');
});
server.listen(3000);
2. APIエンドポイントを構築する
URLモジュールを使用してRESTful APIエンドポイントを構築します:
例
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname;
if (path === '/api/users') {
// ユーザー関連のリクエストを処理する
res.end(JSON.stringify({ users: ['John', 'Jane'] }));
} else if (path === '/api/products') {
// 製品関連のリクエストを処理する
res.end(JSON.stringify({ products: ['Phone', 'Laptop'] }));
} else {
res.statusCode = 404;
res.end('Not Found');
}
});
server.listen(3000);
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname;
if (path === '/api/users') {
// ユーザー関連のリクエストを処理する
res.end(JSON.stringify({ users: ['John', 'Jane'] }));
} else if (path === '/api/products') {
// 製品関連のリクエストを処理する
res.end(JSON.stringify({ products: ['Phone', 'Laptop'] }));
} else {
res.statusCode = 404;
res.end('Not Found');
}
});
server.listen(3000);
3. クエリパラメータを処理する
例
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const query = parsedUrl.query;
if (parsedUrl.pathname === '/search') {
const keyword = query.q || '';
const page = parseInt(query.page) || 1;
res.end(`Searching for "${keyword}" on page ${page}`);
}
});
server.listen(3000);
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const query = parsedUrl.query;
if (parsedUrl.pathname === '/search') {
const keyword = query.q || '';
const page = parseInt(query.page) || 1;
res.end(`Searching for "${keyword}" on page ${page}`);
}
});
server.listen(3000);
ベストプラクティス
- 常にURLを検証する- ユーザーが提供したURLを処理する場合、常にその有効性を検証します
- 新版APIを使用する- 現代の標準により適合するWHATWG URL APIを優先して使用します
- 例外を処理する- try-catchを使用してURL解析で発生する可能性のあるエラーを処理します
- 特殊文字をエンコードする- 使用して
encodeURIComponent()クエリパラメータ内の特殊文字をエンコードします。 - セキュリティに関する考慮事項- リダイレクトを処理するときは、オープンリダイレクトの脆弱性を防ぐためにターゲットURLを検証します
例
// 安全な例:リダイレクトURLを検証する
function isValidRedirect(url) {
const allowedDomains = ['example.com', 'trusted-site.com'];
const parsedUrl = new URL(url);
return allowedDomains.includes(parsedUrl.hostname);
}
function isValidRedirect(url) {
const allowedDomains = ['example.com', 'trusted-site.com'];
const parsedUrl = new URL(url);
return allowedDomains.includes(parsedUrl.hostname);
}
Node.jsのurlモジュールを習得することで、さまざまなURL関連の操作を簡単に処理し、より堅牢で安全なネットワークアプリケーションを構築できます。