node.js - Nodejs new url.URL ("https://myurl.com:80") 将端口列为空

标签 node.js url port

我注意到如果我使用 url 来解析字符串

const url = require('url');
const myUrl = new url.URL("http://myurl.com:80")

生成的对象会将 myUrl.port 列为“”。但是如果我改为设置

const url = require('url');
const myUrl = new url.URL("http://myurl.com:70")

它将把 myUrl.port 列为“70”。

我知道端口 80 是默认端口。但为什么模块要费尽心思去剥离我明确设置的端口呢?

最佳答案

这就是为 Node JS 设计 URL 模块的方式。根据docs

The port value may be a number or a string containing a number in the range 0 to 65535 (inclusive). Setting the value to the default port of the URL objects given protocol will result in the port value becoming the empty string ('').

因此,如果您使用80 (http),它将给出端口的空字符串。 如果您有 https url,例如 https://myurl.com:443,默认端口也将为空字符串。

这里值得注意的是,您分配给请求的协议(protocol)必须与它所采用的默认端口匹配。就像您有这样的网址

https://myurl.com:80 

然后它将返回端口为 80 ,而不是空字符串,因为 https 的默认端口是 443

关于node.js - Nodejs new url.URL ("https://myurl.com:80") 将端口列为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59104197/

相关文章:

javascript - url哈希片段格式

linux - FTP 服务器如何处理来自同一端口的多个连接?

node.js - 连接到azure虚拟机(linux)上的mongodb

javascript - 如何将我的网站连接到我的 Node 应用程序?

javascript - cb 不是 hapi-auth-jwt2 中的函数 - Node.js

mysql - 我无法找到 mysql 代码的错误

php - 将 html <a> 放入 mysql 表文本字段 - url 注入(inject)?

url - 网站的 Unicode url 和 seo 问题

android - 你如何从android http get访问本地端口8080 url

security - 为什么将 docker daemon 绑定(bind)到 0.0.0.0 容易受到攻击?