在 Node.js 中處理 HTTP 請求時,url 模組非常常用。它可以解析 URL、格式化 URL,也能拼接相對路徑。
url.parse 可把字串轉成物件,取出 protocol、host、pathname、search、hash 等欄位。
url.parse('https://user:pass@host.com:8080/p/a/t/h?query=string#hash');若傳入第二個參數 true,query 會被轉成物件;第三個參數 true 則可解析沒有 protocol 的 URL。
url.format 可把物件轉回字串;url.resolve 則可拼接相對路徑。
url.format({
protocol: 'http:',
host: 'www.example.com',
pathname: '/p/a/t/h',
search: 'query=string'
});
url.resolve('https://www.example.com/foo/bar', '../baz');querystring 模組則負責查詢字串與物件之間的轉換:
querystring.parse('foo=bar&baz=qux&baz=quux&corge');
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });這兩個模組搭配使用,就能處理大部分 URL 解析與參數轉換需求。