• Node.js Video Tutorials

NodeJS - url.toJSON() 方法



NodeJS url.toJSON() 方法是 URL 類的方法,它將返回 URL 物件的序列化 URL。此方法的返回值等價於 URL.href 屬性和 URL.toString() 方法。如果分配給 toJSON() 方法的值不是有效的 URL,則會丟擲 TypeError。

Node.js 的 URL 模組提供了各種用於 URL 解析和解析的實用程式,toJSON() 方法就是其中之一。

語法

以下是NodeJS URL 類 toJSON() 方法的語法

URL.toJSON()

引數

此方法不接受任何引數。

返回值

此方法返回 URL 物件的序列化 URL。

示例

如果我們嘗試為 NodeJS url.toJSON() 方法分配一個有效的 URL,則它將返回一個序列化的 URL 字串。

在下面的示例中,我們嘗試從 URL 物件獲取序列化 URL。

const url = require('node:url');
const myURL = new URL("https://tutorialspoint.tw/index.htm");
console.log("The serialized URL: " + myURL.toJSON());

輸出

正如我們在下面的輸出中看到的,NodeJS url.toJSON() 方法返回一個序列化的 URL 字串。

The serialized URL: https://tutorialspoint.tw/index.htm

示例

如果我們為 href 屬性和 toJSON() 方法分配一個有效的 URL,則兩者的返回值是等價的。

在下面的示例中,我們為 href 屬性和 toJSON 方法分配一個有效的 URL,並檢查兩者是否等價。

const url = require('node:url');

const myURL = new URL("https://tutorialspoint.tw/index.htm");

var toJSON = myURL.toJSON();
console.log("Result of toJSON property: " + toJSON);

var href = myURL.href;
console.log("Result of href property: " + href);

if(toJSON === href){
   console.log("Both toJSON and href results are same...");
} else {
   console.log("Both are not same...");
}

輸出

正如我們在下面的輸出中看到的,返回值是相同的。

Result of toJSON property: https://tutorialspoint.tw/index.htm
Result of href property: https://tutorialspoint.tw/index.htm
Both toJSON and href results are same...

示例

如果我們分配一個不是有效 URL 型別的值,則 toJSON() 方法將丟擲 TypeError。

在下面的示例中,我們為 toJSON() 方法分配了一個無效的 URL。

const url = require('node:url');
const myURL = new URL("696wsfsps://www.tutor4523ialspoint.cgfom/ind1234ex.htm");
var result = myURL.toJSON();
console.log("The serialized URL: " + result);

TypeError

如果我們編譯並執行上述程式,toJSON() 方法將丟擲 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: '696wsfsps://www.tutor4523ialspoint.cgfom/ind1234ex.htm',
  code: 'ERR_INVALID_URL'
}
nodejs_url_module.htm
廣告

© . All rights reserved.