URL Module
We can use the. Parse method to convert a URL string to a URL object, as shown below.
1. Description of each part of the URL
var url = require(‘url‘); //加载url模块url.parse(‘http://www.baidu.com‘);
The returned result is:
‘http:‘, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: null, pathname: ‘www.baidu.com‘, path: ‘www.baidu.com‘, href: ‘http://www.baidu.com‘ }
parse函数的第二个参数是布尔类型,当参数为true时,会将查询条件query也解析成json格式的对象
The third argument of the parse function is also a Boolean type, and when the argument is true, parsing will resolve the part between the "//" and the first "/" of the URL to the hostname, as shown in the following example:
var url = require(‘url‘);url.parse(‘http://www.baidu.com/news‘,false,true);
Results returned:
{protocol: ' http: ', slashes: true, auth: null , Host: null, hostname: www.baidu.com ', hash: null, search: null, query : null, pathname: '/news ', Path: / News ', href: ' http://www.baidu.com/news '}
Protocol: Request protocol
Host:url Hostname has all been converted to lowercase, Includes the port information
Auth:url in the Authentication information Section
Hostname: The host name portion of the host that has been converted to lowercase
Port: The port number portion of the host
Pathname:url part of the path, before the host name is requested for the query
Search:url the query string section, including the question mark at the beginning.
Path:pathname and search are linked together.
Query: The parameter part of the query string (the string after the question mark), or the object returned after parsing with Querystring.parse ().
Hash:url "#" after section (including the # symbol)
The format method allows you to convert a URL object to a URL string, as shown below.
The code is as follows:
Url.format ({
Protocol: ' http: ',
Host: ' www.example.com ',
Pathname: '/p/a/t/h ',
Search: ' query=string '
});
/* =
' Http://www.example.com/p/a/t/h?query=string '
*/
.resolve方法可以用于拼接URL,示例如下。
The code is as follows:
Url.resolve (' Http://www.example.com/foo/bar ', ' ... /baz ');
/* =
Http://www.example.com/baz
*/
querystring module
The "QueryString" module is used to convert the URL parameter string to the Parameter object, and a chestnut, as shown below:
Copy CodeThe code is as follows: var URL = require (' URL ');
var qs = require (' querystring ');
var queryurl = "Http://localhost:8888/bb?name=bigbear&memo=helloworld";
Queryurl = Url.parse (queryurl). query;
Console.log (Queryurl);
Console.log (Qs.parse (Queryurl));
Operating results • as follows:
Name=bigbear&memo=helloworld
{
Name: ' Bigbear ',
Memo: ' HelloWorld '
}
URL module and QueryString module