萬盛學電腦網

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

Node.js 解析 URL 獲取路徑與查詢參數

核心模組 url

const 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);

解析任意 URL 字串

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'

現代替代:URL / URLSearchParams

// 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'
copyright © 萬盛學電腦網 all rights reserved