Node.js learning ten (url)

Posted by s3rg1o on Sat, 29 Jan 2022 06:16:19 +0100

preface

A complete url is divided into several parts, such as the following website:
      http://www.tmooc.cn:80/detail.html?lid=5
It consists of the following protocol + domain name + port number + which file on the server to be requested + data passed to the server.
Now let's learn about url in detail.

1, What is a url module

The url module provides utilities for url processing and parsing. You can access it in two ways:

//First kind
import url from 'url';
//Second
const url = require('url');

2, URL string and URL object

The URL string is a structured string containing multiple meaningful components. When resolved, the URL object containing the properties of each component is returned.
Now, the url module provides two API s to handle Web addresses. One is the old version, which is composed of url One of the properties of the object returned by parse () is a new version, which implements the same WHATWG url standard used by Web browsers.
By website ' https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash 'as an example, we are at node JS official website can find the difference between the old and new versions.
On the website‘ https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash 'shows the old URL The property of the object returned by parse(). Below are the properties of the WHATWG URL object.
The origin attribute of WHATWG web address includes protocol and host, but does not include username or password.

1. Use URL Parse() parses the URL string

//Introduce url module
const url = require('url');
//Processing and parsing URL s
var str = 'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'
//Resolve URL to object
var obj = url.parse(str);
console.log(obj)

2. Parsing URL strings using WHATWG API

new URL(input[, base]);

Input < string > absolute or relative input URL to parse. If the input is relative, base is required. If input is absolute, base is ignored.
Base < string > | < URL > if the input is not absolute, it is the basic URL to be parsed.
Create a new URL object by parsing the input relative to the base. If base is passed in as a string, it will be resolved to be equivalent to the new URL(base).
Examples of base usage are as follows:

const myURL = new URL('./foo','https://example.org/');
console.log(myURL.href)

//Introduce url module
const url = require('url');
const myurl = new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
console.log(myurl);


Of which:
protocol: protocol
Host home: host name, domain name (or ip address)
Port: port number
pathname: the path name of the requested file
Query: query string

3, Format the object as a URL (Legacy method)

url.format(URL[, options])

URL < URL > whatwg URL object
options < Object >
Return < string >
Returns the customizable serialization represented by the web address String of the WHATWG web address object.
The URL object has a toString() method and a href attribute, which is used to return the string serialization of the URL. However, none of these can be customized in any way.
      url. The format (URL [, options]) method allows basic customization of the output.
Examples are as follows:

//Introduce url module
const url = require('url');
var obj = {
    protocol:'https',
    hostname:'www.tmooc.cn',
    port:'8080',
    pathname:'detail.html',
    query:{
        lid:5,
        pname:'dell'
    }
}
//Format object as URL
var str = url.format(obj);
console.log(str);


Note: query corresponds to the object.

4, Construct the URL from the component and get the constructed string

1. Property setter and getter of URL class

(1)url.hash

Return < string >
Get and set the fragment part of the URL

const myURL = new URL('https://example.org/foo#bar');
console.log(myURL.hash);

const myURL = new URL('https://example.org/foo');
myURL.hash = 'baz';
console.log(`${myURL}${myURL.hash}`);


Invalid URL characters contained in the value assigned to the hash property are percentage encoded. The characters you select to be percentage encoded may be different from the URL Parse () and URL The format () method produces different results.

(2)url.host

Return < string >
Gets and sets the host part of the web address.

const myURL = new URL('https://example.org:81/foo');
console.log(myURL.host);


Invalid host value assigned to host property will be ignored.

(3)url.hostname

Return < string >
Gets and sets the host name part of the web address. url.host and URL The main difference between hostnames is URL Hostname does not include ports.
Note: setting the host name does not change the port

const myURL = new URL('https://example.org:81/foo');
console.log(myURL.hostname);
myURL.hostname = 'haha.com:82';
console.log(myURL.href);

(4)url.origin

Return < string >
Gets the read-only serialization of the source of the web address.

const myURL = new URL('https://example.org/foo/bar?baz');
console.log(myURL.origin);

(5)url.password

Return < string >
Get and set the password part of the web address.

const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.password);


Invalid URL characters contained in the value assigned to the password property are percentage encoded. The characters you select to be percentage encoded may be different from the URL Parse () and URL The format () method produces different results.

(6)url.pathname

Return < string >
Gets and sets the path part of the web address.

const myURL = new URL('https://example.org/abc/xyz?123');
console.log(myURL.pathname);


Invalid URL characters contained in the value assigned to the pathname attribute are percentage encoded. The characters selected for percentage encoding may be different from the URL Parse () and URL The format () method produces different results.

(7)url.port

Return < string >
Gets and sets the port part of the web address.
The port value can be a number or a string containing numbers from 0 to 65535 inclusive. Setting the value to the default port of the URL object of the given protocol will cause the port value to become an empty string (').
The port value can be an empty string, in which case the port depends on the protocol / scheme:

agreementport
"ftp"21
"file"
"http"80
"https"443
"ws"80
"wss"443

When a value is assigned to a port, it is used first toString() is converted to a string.
If the string is invalid but starts with a number, the leading number is assigned to port. If the number is outside the above range, it will be ignored.

const myURL = new URL('https://example.org:8888');
console.log(myURL.port);
// Reset port number
// The default port is automatically converted to an empty string (the default port of HTTPS protocol is 443)
myURL.port = '443';
console.log('The result is:',myURL.port);
// The result is an empty string
console.log(myURL.href);

(8)url.protocol

Return < string >
Get and set the protocol part of the web address.

const myURL = new URL('https://example.org');
console.log(myURL.protocol);
myURL.protocol = 'ftp';
console.log(myURL.href);

(9)url.search

Return < string >
Gets and sets the serialized query part of the web address.

const myURL = new URL('https://example.org/abc?123');
console.log(myURL.search);
myURL.search = 'abc=xyz';
console.log(myURL.href);


Any invalid URL characters that appear in the value assigned to the search property will be percentage encoded. The characters you select to be percentage encoded may be different from the URL Parse () and URL The format () method produces different results.

(10)url.username

Return < string >
Gets and sets the user name part of the web address.

const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.username);
myURL.username = '123';
console.log(myURL.href);

(11)url.toString()

Return < string >
The toString() method on the URL object returns the serialized URL. The return value is equivalent to URL Href and URL The value of tojson().

(12)url.toJSON()

Return < string >
The toJSON() method on the URL object returns the serialized URL. The return value is equivalent to URL Href and URL The value of tostring().

const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.toString());
console.log(myURL.toJSON());

2. Construct web address

(1) Use the property setter to build the WHATWG web address from the component part

Examples are as follows:

const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh';

(2) Use the template string to build the WHATWG web address from the component part

Examples are as follows:

const pathname = '/a/b/c';
const search = '?d=e';
const hash = '#fgh';
const myURL = new URL(`https://example.org${pathname}${search}${hash}`);

3. Gets the constructed URL string

Using the href attribute accessor

url.href

Return < string >
Gets and sets the serialized web address.
Getting the value of the href attribute is equivalent to calling URL toString().
Setting the value of this property to a new value is equivalent to creating a new URL object using new URL(value). Each property of the URL object will be modified.
If the value assigned to the href attribute is not a valid web address, a TypeError is thrown.

4. Examples

const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh';
console.log(myURL.href);
console.log(myURL.toString());

const pathname = '/a/b/c';
const search = '?d=e';
const hash = '#fgh';
const myURL = new URL(`https://example.org${pathname}${search}${hash}`);
console.log(myURL.href);

Topics: node.js Front-end server