urlconst http = require('http');
const url = require('url');
http.createServer((req, res) => {
// 方法一:只解析 query 字串
var queryStr = url.parse(req.url).query; // "aa=001&bb=002"
// 方法二:直接解析為物件(推薦)
var queryObj = url.parse(req.url, true).query; // {aa:'001', bb:'002'}
console.log(queryObj.aa); // 001
res.end('OK');
}).listen(8888);
var testUrl = 'https://localhost:8888/select?aa=001&bb=002';
var p = url.parse(testUrl);
console.log(p.href); // 完整 URL
console.log(p.protocol); // 'http:'
console.log(p.hostname); // 'localhost'
console.log(p.host); // 'localhost:8888'
console.log(p.port); // '8888'
console.log(p.pathname); // '/select'
console.log(p.path); // '/select?aa=001&bb=002'
console.log(p.query); // 'aa=001&bb=002' (未傳 true 時)
console.log(p.hash); // null
傳 true 時 p.query 為物件:{aa:'001', bb:'002'}。
window.location.href; // 完整 URL
window.location.protocol; // 'http:'
window.location.hostname; // 'example.com'
window.location.port; // '8080'
window.location.pathname; // '/path'
window.location.search; // '?aa=001&bb=002'
window.location.hash; // '#anchor'
// Node.js 10+ / 瀏覽器
const myUrl = new URL('https://localhost:8888/select?aa=001&bb=002');
myUrl.searchParams.get('aa'); // '001'
myUrl.searchParams.getAll('aa'); // ['001']
myUrl.pathname; // '/select'