javascript - 当旧协议在nodejs中包含'+'时为什么不能更新url协议
问题描述
为什么旧协议包含“+”时无法更新 url 协议
这是我的演示测试代码
let u = new URL( 'git+https://url-fake-hostname/zh-TW/scripts')
console.log(u)
u.protocol = 'http:';
console.assert(u.protocol !== 'git+https:', u.protocol)
解决方案
URL 是 Node.js 中的一个特殊对象,因为 Node.js 想让它与浏览器兼容。
有两种方法来构建 URL 对象
- WHATWG URL API
new URL(url)
- 由网络浏览器使用 - 旧版 API
require('url').parse(url)
- 特定于 Node.js
如文件所述:
WHATWG URL 标准认为少数 URL 协议方案在解析和序列化方面是特殊的。当使用这些特殊协议之一解析 URL 时,该
url.protocol
属性可能会更改为另一种特殊协议,但不能更改为非特殊协议,反之亦然。
以下是您遇到的相同案例的一些示例:
const u = new URL('http://example.org');
u.protocol = 'https';
console.log(u.href);
// https://example.org
const u = new URL('http://example.org');
u.protocol = 'fish';
console.log(u.href);
// http://example.org
您可以通过调用 Legacy API 来解决此问题:
const url = require('url');
let u = url.parse( 'git+https://url-fake-hostname/zh-TW/scripts')
u.protocol = 'http:';
console.log(u.protocol);// protocol: 'http:'
推荐阅读
- ios - 为什么没有为 iOS Firebase 动态链接启用通用链接?
- conan - 创建柯南包而不复制源
- django-rest-framework - 使用 DRF 过滤器后端
- java - 如何在列表视图中显示 json 数据?
- powershell - 类名作为变量
- python - 如何使用 django 在数据库中创建一个记录来自 ModelMultipleChoiceField 表单的数据的视图?
- java - 如何迁移数据库?
- php - 如何修复我的占位符未显示在表单 Codeigniter 中
- oracle - Oracle SQL 函数实现
- rest - ExtJS 存储执行的 REST 请求失败