url模块
//引入url模块
var myUrl = request('url')
url.hash
获取及设置URL的分段(hash)部分。
var myUrl = require('url');
var myURL = new myUrl('https://example.org/foo#bar');
console.log(myURL.hash);
// 输出 #bar
//赋值
myURL.hash = 'baz';
console.log(myURL.href);
// 输出 https://example.org/foo#baz
包含在赋给hash
属性的值中的无效URL字符是百分比编码。请注意选择哪些字符进行百分比编码可能与url.parse()和url.format()方法产生的不同。
url.host
获取及设置URL的主机(host)部分。
var Url = require('url');
var myURL = new Url('https://example.org:81/foo');
console.log(myURL.host);
// 输出 example.org:81
myURL.host = 'example.com:82';
console.log(myURL.href);
// 输出 https://example.com:82/foo
如果给host
属性设置的值是无效值,那么该值将被忽略。
url.hostname
获取及设置URL的主机名(hostname)部分。 url.host
和url.hostname
之间的区别是url.hostname
不 包含端口。
var URL = require('url');
const myURL = new URL('https://example.org:81/foo');
console.log(myURL.hostname);
// 输出 example.org
myURL.hostname = 'example.com:82';
console.log(myURL.href);
// 输出 https://example.com:81/foo
如果给hostname
属性设置的值是无效值,那么该值将被忽略。
url.href
获取及设置序列化的URL。
var URL = require('url');
const myURL = new URL('https://example.org/foo');
console.log(myURL.href);
// 输出 https://example.org/foo
myURL.href = 'https://example.com/bar';
console.log(myURL.href);
// 输出 https://example.com/bar
获取href
属性的值等同于调用url.toString()
。
将此属性的值设置为新值等同于new URL(value)
使用创建新的URL
对象。URL
对象的每个属性都将被修改。
如果给href
属性设置的值是无效URL,将会抛出TypeError
。
url.origin
获取只读序列化的URL origin部分。
const { URL } = require('url');
const myURL = new URL('https://example.org/foo/bar?baz');
console.log(myURL.origin);
// 输出 https://example.org
const { URL } = require('url');
const idnURL = new URL('https://你好你好');
console.log(idnURL.origin);
// 输出 https://xn--6qqa088eba
console.log(idnURL.hostname);
// 输出 xn--6qqa088eba
url.password
获取及设置URL的密码(password)部分。
url.pathname
获取及设置URL的路径(path)部分。
url.port
获取及设置URL的端口(port)部分。
url.parse(urlString[, parseQueryString[, slashesDenoteHost]])
-
urlString
要解析的 URL 字符串 -
``parseQueryString
如果为
true,则
query属性总会通过 [
querystring](http://nodejs.cn/s/i23Gdh) 模块的
parse()方法生成一个对象。 如果为
false,则返回的 URL 对象上的
query属性会是一个未解析、未解码的字符串。 默认为
false`。 -
url.parse()
方法会解析一个 URL 字符串并返回一个 URL 对象。如果
urlString
不是字符串将会抛出TypeError
。如果
auth
属性存在但无法编码则抛出URIError
。
var myurl = require('url') //parse里面的第二个参数默认为false,获取id时,必须修改成true var id = myurl.parse(req.url,true).query.id
网友评论