處理 HTTP 請求時,URL 模組使用率極高,支援解析、生成、拼接 URL。一個完整 URL 結構如下:
href
-----------------------------------------------------------------
host path
--------------- ----------------------------
https:// user:pass @ host.com : 8080 /p/a/t/h ?query=string #hash
----- --------- -------- ---- -------- ------------- -----
protocol auth hostname port pathname search hash
------------
query
將 URL 字串轉換為 URL 物件:
url.parse('https://user:pass@host.com:8080/p/a/t/h?query=string#hash');
/* 回傳:
{
protocol: 'http:',
auth: 'user:pass',
host: 'host.com:8080',
port: '8080',
hostname: 'host.com',
hash: '#hash',
search: '?query=string',
query: 'query=string', // 若 parseQueryString=true 則為物件 {query:'string'}
pathname: '/p/a/t/h',
path: '/p/a/t/h?query=string',
href: 'https://user:pass@host.com:8080/p/a/t/h?query=string#hash'
}
*/
http.createServer(function(req, res) {
var tmp = req.url; // 例:"/foo/bar?a=b"
url.parse(tmp);
/* 回傳:
{ protocol: null, slashes: null, auth: null, host: null, port: null,
hostname: null, hash: null, search: '?a=b', query: 'a=b',
pathname: '/foo/bar', path: '/foo/bar?a=b', href: '/foo/bar?a=b' }
*/
}).listen(80);
parseQueryString=true:query 欄位回傳 querystring 模組解析後的物件,而非字串。slashesDenoteHost=true:可正確解析無協定頭的 URL(如 //www.example.com/foo/bar)。將 URL 物件轉回字串:
url.format({
protocol: 'http:',
host: 'www.example.com',
pathname: '/p/a/t/h',
search: 'query=string'
});
// 回傳:'https://www.example.com/p/a/t/h?query=string'
依相對路徑規則拼接 URL:
url.resolve('https://www.example.com/foo/bar', '../baz');
// 回傳:'https://www.example.com/baz'
querystring.parse('foo=bar&baz=qux&baz=quux&corge');
// 回傳:{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
// 回傳:'foo=bar&baz=qux&baz=quux&corge='
掌握 URL 模組與 querystring,能輕鬆處理路由解析、參數驗證、重導向等常見後端任務,是 Node.js 開發必備基石。