• Node.js Video Tutorials

NodeJS - url.href 屬性



URL 類的NodeJS url.href 屬性用於獲取和設定序列化後的 URL。獲取 href 屬性的值類似於呼叫 toString() 方法。Node.js URL 模組提供了多個用於 URL 解析和處理的實用程式,href 屬性就是其中之一。

如果嘗試將此屬性的值設定為新值,則等效於使用 new URL(value) 建立新的 URL 物件。URL 物件的每個屬性都將根據新值進行修改。

語法

以下是NodeJS URL 類 href 屬性的語法

URL.href

引數

此屬性不接受任何引數。

返回值

此屬性允許我們獲取和設定序列化後的 URL。

以下是 Node.js URL 模組中NodeJS URL.href 屬性的示例。

示例

我們可以使用 NodeJS URL.href 屬性獲取給定的序列化 URL。

在下面的示例中,我們嘗試透過將 URL 分配給 NodeJS href 屬性來獲取序列化 URL。

const url = require('url');

const myURL = new URL('https://tutorialspoint.tw/index.htm');
console.log(myURL.href);

輸出

正如我們在下面的輸出中看到的,NodeJS URL.href 屬性返回了序列化後的 URL。

https://tutorialspoint.tw/index.htm

示例

我們可以使用 URL.href 屬性設定給定的序列化 URL。

在下面的程式中,我們嘗試使用 URL.href 屬性修改給定的 URL。

const url = require('url');

const myURL = new URL('https://tutorialspoint.tw/index.htm');
console.log("Before modifying the URL: " + myURL);

myURL.href = "https://www.Tutorix.com/index.htm";
console.log("After modifying the URL: " + myURL.href);

輸出

執行上述程式後,URL.href 屬性已修改並返回了序列化後的 URL。

Before modifying the URL: https://tutorialspoint.tw/index.htm
After modifying the URL: https://www.tutorix.com/index.htm

示例

我們還可以透過呼叫 URL.toString() 方法來獲取 URL.href 屬性的值。

在下面的示例中,我們嘗試使用 URL.toString() 方法獲取序列化 URL。

const url = require('url');

const myURL = new URL('https://www.Tutorix.com/index.htm');
console.log("Before modifying the URL: " + myURL);

myURL.href = "https://tutorialspoint.tw/index.htm";
const result = myURL.href;
console.log("After modifying the URL: " + result.toString());

輸出

正如我們在下面的輸出中看到的,URL.toString() 返回的值與 URL.href 屬性相同。

Before modifying the URL: https://www.tutorix.com/index.htm
After modifying the URL: https://tutorialspoint.tw/index.htm

示例

如果我們賦值的值不是有效的 URL 型別,則 href 屬性將丟擲 TypeError。

在給定的程式中,我們將無效的 URL 分配給 href 屬性。

const url = require('url');

const myURL = new URL(43478998765);
console.log("Before modifying the URL: " + myURL.href);

TypeError

如果我們編譯並執行上述程式,href 屬性將丟擲 TypeError,因為分配的 URL 無效。

node:internal/url:564
  throw new ERR_INVALID_URL(input);
  ^

TypeError [ERR_INVALID_URL]: Invalid URL
    at new NodeError (node:internal/errors:387:5)
    at URL.onParseError (node:internal/url:564:9)
    at new URL (node:internal/url:640:5)
    at Object.<anonymous> (C:\Users\Lenovo\Desktop\JavaScript\nodefile.js:3:15)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  input: '43478998765',
  code: 'ERR_INVALID_URL'
}
nodejs_url_module.htm
廣告
© . All rights reserved.