」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > URL對象

URL對象

發佈於2024-11-08
瀏覽:634

The URL Object

概述

JavaScript 中的 URL 物件提供了一種輕鬆使用和操作 URL 的方法。當您需要在程式碼中建構、解析或修改 URL 時,它特別有用。

很多時候使用模板字串來在 JavaScript 中建立 URL。通常這很簡單且足夠清晰,但 URL 物件是處理 URL 的更強大的 OOP 方法。

甚至OpenWeatherMap.org 在文件中也使用模板字串:https://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&exclude={part}&appid= {API key }

對於相當靜態的 URL,這很好,但如果您想更改此 URL,您可能需要考慮使用 URL 物件。

// Using template strings
const lat = 32.087;
const lon = 34.801;
const apiKey = 'your_api_key';
const url = `https://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&appid=${apiKey}`;

// Using the URL object
const openWeatherUrl = new URL('https://api.openweathermap.org/data/3.0/onecall');
openWeatherUrl.searchParams.set('lat', lat);
openWeatherUrl.searchParams.set('lon', lon);
openWeatherUrl.searchParams.set('appid', apiKey);

基本用法

您可以透過將 URL 字串傳遞給其建構函式來建立新的 URL 物件。

在這種情況下(與上面相反),整個 URL 與各個部分一起傳入:

const url = new URL('https://example.com:8080/path?query=123#section');

特性

URL 物件有幾個屬性,您可以使用它們來存取 URL 的各個部分:

  • href:字串形式的完整 URL。
  • 協議:協議(例如 https:)。
  • 主機名稱:網域名稱(例如 example.com)。
  • port:連接埠號(例如 8080)。
  • 路徑名:網域名稱後面的路徑(例如/path)。
  • search:查詢字串,包括? (例如?query=123)。
  • hash:片段標識符,包括#(例如#section)。
  • 主機:主機名稱和連接埠組合(例如 example.com:8080)。
  • origin:URL 的來源,即協定、主機名稱和連接埠。
> const url = new URL('https://example.com:8080/path?query=123#section');
> url.port
'8080'
> url.protocol
'https:'
> url.hostname
'example.com'
> url.pathname
'/path'
> url.search
'?query=123'
> url.hash
'#section'
> url.host
'example.com:8080'

這些也可用於更改 URL 的不同部分? :

> url.port = 1234
1234
> url.pathname = "differentpath"
'differentpath'
> url.hostname = "example.org"
'example.org'
> url
URL {
  href: 'https://example.org:1234/differentpath?query=123#section',
  origin: 'https://example.org:1234',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'example.org:1234',
  hostname: 'example.org',
  port: '1234',
  pathname: '/differentpath',
  search: '?query=123',
  searchParams: URLSearchParams { 'query' => '123' },
  hash: '#section'
}

方法

URL物件還有一些方法可以幫助修改URL並與URL互動。

例如,URL 搜尋參數 是一個鍵值對,用於通知 API 伺服器詳細資訊以服務使用者。

url.searchParams:傳回 URLSearchParams 對象,該對象提供使用查詢字串參數的方法。你可以:

取得查詢參數:url.searchParams.get('query')
設定查詢參數: url.searchParams.set('query', '456')
刪除查詢參數: url.searchParams.delete('query')

迭代查詢參數:

url.searchParams.forEach((value, key) => {
  console.log(key, value);
});

toString():以字串形式傳回完整 URL,反映對屬性或查詢參數所做的任何變更。

開放天氣圖 API 範例

以下是 OpenWeatherMap 的文檔:https://openweathermap.org/api/one-call-3

這是一個簡單的範例,展示如何建立 URL 物件並操作其各個部分:

// get values to interpolate to URL
const apiKey = process.env.openWeatherApiKey || 0
const [lat, lon] = [32.08721095615897, 34.801588162316506]

const openWeatherUrl = new URL("https://api.openweathermap.org")

openWeatherUrl.pathname = "data/3.0/onecall"
openWeatherUrl.searchParams.set('lat',lat)
openWeatherUrl.searchParams.set('lon',lon)

// from the docs
openWeatherUrl.searchParams.set('exclude', 'hourly')

openWeatherUrl.searchParams.set('appid', apiKey)

console.log(openWeatherUrl)

輸出:

URL {
  href: 'https://api.openweathermap.org/data/3.0/onecall?lat=32.08721095615897&lon=34.801588162316506&exclude=hourly&appid=0',
  origin: 'https://api.openweathermap.org',
  protocol: 'https:',
  username: '',
  password: '',
  host: 'api.openweathermap.org',
  hostname: 'api.openweathermap.org',
  port: '',
  pathname: '/data/3.0/onecall',
  search: '?lat=32.08721095615897&lon=34.801588162316506&exclude=hourly&appid=0',
  searchParams: URLSearchParams {
    'lat' => '32.08721095615897',
    'lon' => '34.801588162316506',
    'exclude' => 'hourly',
    'appid' => '0' },
  hash: ''
}

概括

JavaScript 中的 URL 物件提供了一種處理 URL 的結構化方法,可輕鬆操作和建立複雜的 URL。雖然模板字串對於靜態 URL 來說簡單且有效,但 URL 物件對於 URL 是動態的或需要頻繁修改的情況來說是理想的選擇。


照片由 Anne Nygård 在 Unsplash 上拍攝

版本聲明 本文轉載於:https://dev.to/wolfmath/the-url-object-3485?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3