url.port是url模塊中的類URL的內置應用程序編程接口,用於獲取和設置URL的端口部分。端口值可以是數字或包含0到65535(包括的)。將值設置為給定協議的URL對象的默認端口將導致端口值變為空字符串(“)。端口值可以是空字符串,在這種情況下,端口取決於協議/方案:
協議 | 端口 |
---|---|
“ftp” | 21 |
“file” | |
“gopher” | 70 |
“http” | 80 |
“https” | 443 |
“ws” | 80 |
“wss” | 443 |
為端口分配值後,首先將使用.toString()將值轉換為字符串。如果該字符串無效,但以數字開頭,則將前導號分配給端口。如果數字超出上述範圍,則將其忽略。
用法:
const url.port
返回值:它獲取並設置URL的端口部分。
以下示例程序旨在說明url.port方法的用法:
範例1:
// node program to demonstrate the
// url.port API as Setter
//importing the module 'url'
const http = require('url');
// creating and initializing myURL
const myURL = new URL('https://example.com:80/foo#ram');
// Display href and port
// value of myURL before change
console.log("Before Change");
console.log(myURL.href);
// assinging port portion
// using port API
console.log();
myURL.port = '12345';
// Display href and password
// value of myURL after change
console.log("After Change");
console.log(myURL.href);
輸出:
Before Change https://example.com:80/foo#ram After Change https://example.com:12345/foo#ram
範例2: 如果端口號是半數字和半字母
// node program to demonstrate the
// url.port API as Setter
//importing the module 'url'
const http = require('url');
// creating and initializing myURL
const myURL = new URL('https://example.com:80/foo#ram');
// Display href and port
// value of myURL before change
console.log("Before Change");
console.log(myURL.href);
// assinging port portion
// using port API
console.log();
myURL.port = '2580abcd';
// Display href and password
// value of myURL after change
console.log("After Change");
console.log(myURL.href);
輸出:
Before Change https://example.com:80/foo#ram After Change https://example.com:2580/foo#ram
範例3:
// node program to demonstrate the
// url.port API as Getter
//importing the module 'url'
const http = require('url');
// creating and initializing myURL
const myURL = new URL('https://example.org/foo#ram');
myURL.port = '1234'
// getting the port portion
// using port
const port = myURL.port;
// Display port value
console.log("port is:" + port);
//"https" default port is 443
console.log("After Change");
myURL.port = '443';
console.log(myURL.port);
輸出:
port is:1234 After Change prints Empty String // myURL.port = 443 - Default port for https // Therefore ignored by NodeJS - URL
注意:以上程序將通過在Node上使用myapp.js命令進行編譯和運行。
參考:
https://nodejs.org/api/url.html#url_url_port
相關用法
- Node.js URLSearchParams.set()用法及代碼示例
- Node.js URL.protocol用法及代碼示例
- Node.js URL.hostname用法及代碼示例
- Node.js URL.href用法及代碼示例
- Node.js URL.hash用法及代碼示例
- Node.js URL.host用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Node | URL.port API。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。