在 Node.js 中解析 URL 是相當頻繁的需求——路由判斷、取出 query 參數、記錄來源頁面等等。內建的 url 模組就能勝任,本文直接以程式碼示範。
// 需要的模組:http、url
// 假設目前的網址是 https://localhost:8888/select?aa=001&bb=002
var http = require('http');
var url = require('url');
http.createServer(function (req, res) {
var arg = url.parse(req.url).query; // 方法一:arg => "aa=001&bb=002"
var arg = url.parse(req.url, true).query; // 方法二:arg => { aa: '001', bb: '002' }
console.log(arg.aa); // 001
console.log(arg.bb); // 002
// 接著就能依取得的資料進行處理
}).listen(8888); // 建立伺服器並監聽連接埠
兩種寫法的差別就在第二個參數:parse(urlStr, true) 會自動用 querystring 把查詢字串解析成物件,省去自己拆字的工作,實務上幾乎都用這種。
var testUrl = 'https://localhost:8888/select?aa=001&bb=002'; var p = url.parse(testUrl); console.log(p.href); // https://localhost:8888/select?aa=001&bb=002 console.log(p.protocol); // http: console.log(p.hostname); // localhost console.log(p.host); // localhost:8888 console.log(p.port); // 8888 console.log(p.path); // /select?aa=001&bb=002 console.log(p.pathname); // /select console.log(p.query); // aa=001&bb=002 console.log(p.hash); // null
值得注意的是,當寫成 url.parse(testUrl, true) 時,p.query 會變成物件 { aa: '001' }。此時直接 console.log(p.query) 只會印出 [object Object],必須個別取值:
console.log(p.query.aa); // 001
host 與 hostname 的區別也值得記:前者包含連接埠,後者只有主機名稱。
Node.js 現在推薦使用 WHATWG 標準的 URL 類別,API 更直覺,也與瀏覽器一致:
const { URL } = require('url');
const myURL = new URL('https://localhost:8888/select?aa=001&bb=002');
console.log(myURL.hostname); // localhost
console.log(myURL.port); // 8888
console.log(myURL.pathname); // /select
console.log(myURL.searchParams.get('aa')); // 001
console.log(myURL.searchParams.get('bb')); // 002
在 HTTP 伺服器中,直接寫 new URL(req.url, 'https://localhost') 即可。searchParams 還支援 getAll()(同名參數多值)、has()、append() 等方法,比字串處理方便得多。
https://mj_0203.0fees.net/index.php?aa=001&bb=002 document.location // 完整網址 document.URL // 完整網址 document.location.href // 完整網址 self.location.href // 完整網址 top.location.href // 最上層視窗的網址 parent.document.location // 父頁面的網址 top.location.hostname // mj_0203.0fees.net location.hostname // mj_0203.0fees.net
在瀏覽器中,更推薦用 new URLSearchParams(location.search) 來取參數,寫法與 Node 端完全相同,前後端程式碼可以共用同一套邏輯。