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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。