📜  Node.js URL.origin API(1)

📅  最后修改于: 2023-12-03 15:03:14.475000             🧑  作者: Mango

Node.js URL.origin API

Node.js URL.origin API是Node.js的一个模块,它提供了方便的URL解析和操作方法,并且可以用于构建URL字符串。在这篇文章中,我们将会从以下几个方面来介绍Node.js URL.origin API:

  1. 什么是URL.origin?

  2. Node.js URL.origin API的使用方法

  3. 实例演示

1. 什么是URL.origin?

URL.origin是指URL的源(原始)部分,包括协议(protocol)、主机名(hostname)和端口(port),但不包括路径(path)和查询(query)部分。它通常用于创建或验证同源策略(same-origin policy),这是一种Web安全政策,它指定了哪些JavaScript能够访问网页的哪些部分。

2. Node.js URL.origin API的使用方法

Node.js URL.origin API提供了parse()和format()两个方法,分别用于解析和构建URL。

2.1 URL.parse()方法

URL.parse()方法用于解析URL字符串,返回一个对象,包含了URL的各个组成部分。该方法的语法如下:

const { URL } = require('url');
const myUrl = new URL('/foo', 'https://example.org/');
console.log(myUrl.origin); // 输出: 'https://example.org'
2.2 URL.format()方法

URL.format()方法用于从解析后的URL对象中创建URL字符串。该方法的语法如下:

const { URL } = require('url');
const myUrl = new URL('/foo?bar=baz', 'https://example.org/');
console.log(myUrl.href); // 输出: 'https://example.org/foo?bar=baz'
3. 实例演示

下面是一个使用Node.js URL.origin API进行URL解析和构建的实例:

const { URL } = require('url');
const myUrl = new URL('https://example.org/foo?bar=baz');
console.log(myUrl.origin); // 输出: 'https://example.org'
console.log(myUrl.searchParams.get('bar')); // 输出: 'baz'

myUrl.searchParams.append('key', 'value');
console.log(myUrl.href); // 输出: 'https://example.org/foo?bar=baz&key=value'

const newUrl = new URL('https://example.org/new');
console.log(newUrl.href); // 输出: 'https://example.org/new'

const fullUrl = URL.format({
  protocol: 'https',
  hostname: 'example.org',
  pathname: '/foo',
  search: '?bar=baz'
});
console.log(fullUrl); // 输出: 'https://example.org/foo?bar=baz'

以上就是Node.js URL.origin API的介绍和演示。希望这篇文章可以帮助到你更好地使用Node.js URL操作相关的功能。