new URL(input[, base])
input<string> 要解析的绝对或相对输入 URL。如果input是相对的,则需要base。如果input是绝对的,则忽略base。如果input不是字符串,则首先是converted to a string。base<string> 如果input不是绝对的,则要解析的基本 URL。如果base不是字符串,则首先是converted to a string。
通过解析相对于 base 的 input 创建一个新的 URL 对象。如果 base 作为字符串传递,它将被解析为等同于 new URL(base) 。
const myURL = new URL('/foo', 'https://example.org/');
// https://example.org/foo
URL 构造函数可作为全局对象的属性进行访问。也可以从内置的 url 模块导入:
import { URL } from 'node:url'; console.log(URL === globalThis.URL); // Prints 'true'.console.log(URL === require('node:url').URL); // Prints 'true'.
如果 input 或 base 不是有效的 URL,则会抛出 TypeError。请注意,将努力将给定的值强制转换为字符串。例如:
const myURL = new URL({ toString: () => 'https://example.org/' });
// https://example.org/
input 的主机名中出现的 Unicode 字符将使用 Punycode 算法自动转换为 ASCII。
const myURL = new URL('https://測試');
// https://xn--g6w251d/
此函数仅在 node 可执行文件在启用 ICU 的情况下编译时可用。如果不是,则域名原封不动地通过。
如果事先不知道 input 是否是绝对 URL 并且提供了 base,建议验证 URL 对象的 origin 是否是预期的。
let myURL = new URL('http://Example.com/', 'https://example.org/');
// http://example.com/
myURL = new URL('https://Example.com/', 'https://example.org/');
// https://example.com/
myURL = new URL('foo://Example.com/', 'https://example.org/');
// foo://Example.com/
myURL = new URL('http:Example.com/', 'https://example.org/');
// http://example.com/
myURL = new URL('https:Example.com/', 'https://example.org/');
// https://example.org/Example.com/
myURL = new URL('foo:Example.com/', 'https://example.org/');
// foo:Example.com/
相关用法
- Node.js new URLSearchParams(obj)用法及代码示例
- Node.js new URLSearchParams(iterable)用法及代码示例
- Node.js new URLSearchParams(string)用法及代码示例
- Node.js new assert.AssertionError(options)用法及代码示例
- Node.js new AsyncResource(type[, options])用法及代码示例
- Node.js new stream.Duplex(options)用法及代码示例
- Node.js new stream.Readable([options])用法及代码示例
- Node.js new Console(options)用法及代码示例
- Node.js new crypto.Certificate()用法及代码示例
- Node.js new stream.Writable([options])用法及代码示例
- Node.js new Agent([options])用法及代码示例
- Node.js new vm.SourceTextModule(code[, options])用法及代码示例
- Node.js new stream.Transform([options])用法及代码示例
- Node.js new PerformanceObserver(callback)用法及代码示例
- Node.js new assert.CallTracker()用法及代码示例
- Node.js net.isIP(input)用法及代码示例
- Node.js net.createConnection(options[, connectListener])用法及代码示例
- Node.js net.isIPv6(input)用法及代码示例
- Node.js net.Server.address()用法及代码示例
- Node.js net.createServer([options][, connectionListener])用法及代码示例
- Node.js net.Server.listen()用法及代码示例
- Node.js net.Socket.setTimeout(timeout[, callback])用法及代码示例
- Node.js net.BlockList.check(address[, type])用法及代码示例
- Node.js net.isIPv4(input)用法及代码示例
- Node.js ServerHttp2Stream http2stream.pushStream(headers[, options], callback)用法及代码示例
注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 new URL(input[, base])。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
