萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Node.js URL 模組完整指南:parse、format、resolve 與 querystring 實戰

URL 結構拆解

處理 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.parse(urlStr[, parseQueryString[, slashesDenoteHost]])

將 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'
}
*/

處理不完整 URL(如 HTTP 回調中的 request.url)

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.format(urlObj)

將 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.resolve(from, to)

依相對路徑規則拼接 URL:

url.resolve('https://www.example.com/foo/bar', '../baz');
// 回傳:'https://www.example.com/baz'

querystring 模組:參數字串與物件互轉

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 開發必備基石。

copyright © 萬盛學電腦網 all rights reserved