1. 程式人生 > >極簡 Node.js 入門 - 5.2 url & querystring

極簡 Node.js 入門 - 5.2 url & querystring

> 極簡 Node.js 入門系列教程:[https://www.yuque.com/sunluyong/node](https://www.yuque.com/sunluyong/node) > > 本文更佳閱讀體驗:[https://www.yuque.com/sunluyong/node/url-qs](https://www.yuque.com/sunluyong/node/url-qs) 在處理 web 資訊的時候經常需要解析 url,Node.js 提供了方便的處理模組 ## URL 規範 URL 全稱是 uniform resource locator,統一資源定位符,根據一個 url 能夠在全球確定一個唯一的資源,URL 由不同的欄位組成,`url` 模組提供了兩套 API 來處理 URL:一個是舊版本遺留的 API,一個是實現了 [WHATWG標準](https://url.spec.whatwg.org/)的新 API。為了避免混淆,下文只介紹目前通用的 WHATWG 標準 ``` " https: // user : pass @ sub.example.com : 8080 /p/a/t/h ? query=string #hash " │ │ │ │ │ hostname │ port │ │ │ │ │ │ │ │ ├─────────────────┴──────┤ │ │ │ │ protocol │ │ username │ password │ host │ │ │ │ ├──────────┴──┼──────────┴──────────┼────────────────────────┤ │ │ │ │ origin │ │ origin │ pathname │ search │ hash │ ├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤ │ href │ ``` ## URL 類 Node.js 中的 URL 類和[瀏覽器 URL API ](https://developer.mozilla.org/zh-CN/docs/Web/API/URL)完全相容,可以通過 `require('url').URL` 使用,也可以使用全域性變數 `URL`  ```javascript console.log(URL === require('url').URL); // true ``` new URL(input[, base]):例項化一個 URL 物件 1. input:要解析的絕對或相對的 URL。如果 `input` 是相對路徑,則需要 `base`;如果 `input` 是絕對路徑,則忽略 `base` 1. base:如果 `input` 不是絕對路徑,則為要解析的基礎地址 ```javascript const myURL = new URL('/foo', 'https://example.org/'); // https://example.org/foo ``` ### URL 例項屬性 -  url.hash - url.host - url.hostname - url.href - url.origin - url.password - url.pathname - url.port - url.protocol - url.search - url.serachParam - url.username
URL 規範中的所有欄位都可以從 URL 例項中讀取,也可以對屬性進行修改 ```javascript const myURL = new URL('https://abc:[email protected]'); console.log(myURL.username); // abc myURL.username = '123'; console.log(myURL.href); // https://123:[email protected]/ ``` 解析 url 的檔名可以結合 `path` 模組 ```javascript const path = require('path'); const { pathname } = new URL('/foo/bar.txt', 'https://example.org/'); console.log(path.basename(pathname)); // bar.txt console.log(path.parse(pathname)); ``` ## querystring URL 例項中返回的 `search` 是querystring 的完整字串,並不是鍵值對的格式,對 querystring 操作可以使用 `url.serachParam` 屬性,該屬性是 `URLSearchParams` 類例項,同時也是個迭代器,有幾個常用的方法操作 querystring
- urlSearchParams.get(name) - urlSearchParams.set(name, value) - urlSearchParams.delete(name) - urlSearchParams.append(name, value) - urlSearchParams.forEach(fn[, thisArg])
使用都非常簡單 ```javascript const myURL = new URL('https://example.org/?abc=123'); console.log(myURL.searchParams.get('abc')); // 123 myURL.searchParams.append('abc', 'xyz'); console.log(myURL.href); // https://example.org/?abc=123&abc=xyz myURL.searchParams.delete('abc'); myURL.searchParams.set('a', 'b'); console.log(myURL.href); // https://example.org/?a=b ``` >
在較早的版本使用 Node.js 內建模組 `querystring` 來操作 url querystring,簡單場景可以不