首页 > 解决方案 > 当旧协议在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)

标签: javascriptnode.jstypescript

解决方案


URL 是 Node.js 中的一个特殊对象,因为 Node.js 想让它与浏览器兼容。

有两种方法来构建 URL 对象

  1. WHATWG URL API new URL(url) - 由网络浏览器使用
  2. 旧版 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:'

推荐阅读