当前位置:网站首页>Nodejs Foundation: shallow chat URL and querystring module
Nodejs Foundation: shallow chat URL and querystring module
2022-07-03 03:51:00 【Little pig brother】
url modular
url What is it? ? To put it simply url Global resource locator , A concise expression of website resources , Also known as the web address .
Now take a look url Three parts of the format :
https://blog.csdn.net/u011863822?spm=1000.2115.3001.5343
- The first part is the agreement ( Or service mode ), The general website is http perhaps https. So the protocol in the example is https.
- The second part is the host where the resource is stored IP Address ( Sometimes a port number is also included ). But for better records, there are domain names , Generally speaking www At the beginning , For example, Baidu. www.baidu.com , But it is not absolutely natural that some people do not abide by the rules of the World Wide Web , such as csdn The middle is blog.csdn.net.
- The third part is the specific address of the host resource , Such as directories and file names . This is the location of the requested resource in the domain name , It's like the domain name is D disc , And your file still needs to have a more detailed address .
You can also add ?
Parameters are followed , In especial get The parameters in the request are more meaningful .
and url Module is to help deal with url A module of , For example, how to know the directory address in the example , And if the domain name may be processed, string segmentation and other operations are required , however url But it can help us deal with it better , Now let's take a look at the common methods .
Outdated common methods
parse Method
Let's experience it first :
var url= require('url')
const url_html='https://blog.csdn.net/u011863822?spm=1000.2115.3001.5343'
console.log(url.parse(url_html))
Look at the output :
It can be seen that the URL request , So you can see the information of all the addresses requested , Don't use regular or split strings by yourself , This module .
After all, through req.url With parameters , You need to split this url String , Use this to pass through pathname Get the requested address , It's not very fragrant .
Actually, there can be two parameters :
var url= require('url')
const url_html='https://blog.csdn.net/u011863822?spm=1000.2115.3001.5343'
console.log(url.parse(url_html,true))
It can be seen that query The parameter of becomes a object, More convenient .
format() Method
Since it can become a urlObject, Nature can also pass through urlObject Convert to a url.
var url= require('url')
const urlobjct= {
protocol: 'https:',
slashes: true,
auth: null,
host: 'blog.csdn.net',
port: null,
hash: null,
search: '?spm=1000.2115.3001.5343',
query: 'spm=1000.2115.3001.5343',
pathname: '/u011863822',
path: '/u011863822?spm=1000.2115.3001.5343',
href: 'https://blog.csdn.net/u011863822?spm=1000.2115.3001.5343'
}
console.log(url.format(urlobjct))
resolve Method
Format :
resolve(from, to)
- from If to Is relative URL, Then use the basic URL.
- to The target to be resolved URL.
url.resolve() The method is similar to Web The way the browser parses anchor tags is relative to basic URL The goal of URL.
It's still the old rule , This official website example , Direct use .
const url = require('url');
// If the front end is not / There's no back / Just replace the front / Later
url.resolve('/one/two/three', 'four'); // '/one/two/four'
// If the front end is / There's no back / Just put it directly in front / Back
url.resolve('/one/two/three/', 'four'); // '/one/two/three/four'
// If there's something in the back / Just put it directly in front / After the domain name
url.resolve('http://example.com/', '/one'); // 'http://example.com/one'
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
Look at the official website and find that the prompt is out of date
The above three methods are actually written in the old version , Of course, since it's an old version, there are new versions , So let's talk about the implementation of the new version .
New common methods or classes
new ULR() Method
This can be called directly , Instead of referencing modules ,
Format :
new URL(input[, base])
- input Absolute or relative input URL to parse . If input Is relative , You need to base. If input Absolutely , It ignores base. If input It's not a string , First convert it into a string .
- base If input Not absolutely , Is the basic web address to be parsed . If base It's not a string , First convert it into a string .
Let's take an example :
const urlobjct=new URL('/u011863822?spm=1000.2115.3001.5343','https://blog.csdn.net')
console.log(urlobjct)
You can see the above results and url.parse The result of the method is the same , You can also take out different contents according to your own needs .
const url = require('url');
// If the front end is not / There's no back / Just replace the front / Later
url.resolve('http://example.com/one/two/three', 'four'); // 'http://example.com/one/two/four'
// If the front end is / There's no back / Just put it directly in front / Back
url.resolve('http://example.com/one/two/three/', 'four'); // 'http://example.com/one/two/three/four'
// If there's something in the back / Just put it directly in front / After the domain name
url.resolve('http://example.com/', '/one'); // 'http://example.com/one'
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
// It can become :
let b_url=new URL('four', 'http://example.com/one/two/three');
console.log(b_url.href)
b_url=new URL('/four', 'http://example.com/one/two/three');
console.log(b_url.href)
b_url=new URL('/one', 'http://example.com/');
console.log(b_url.href)
b_url=new URL('/two', 'http://example.com/one');
console.log(b_url.href)
URLSearchParams class
URLSearchParams API Provide right URL Read write access to queries . URLSearchParams Class can also be used alone with one of the following four constructors . URLSearchParams Classes are also available on global objects .
WHATWG URLSearchParams Interface and querystring Modules have similar uses , but querystring The purpose of the module is more general , Because it allows custom delimiters (& and =). let me put it another way , this API It is purely designed for URL query strings .
Take an example of the official website :
const myURL = new URL('https://example.org/?abc=123');
console.log(myURL.searchParams.get('abc'));
// Print 123
myURL.searchParams.append('abc', 'xyz');
console.log(myURL.href);
// Print https://example.org/?abc=123&abc=xyz
myURL.searchParams.delete('abc');
myURL.searchParams.set('a', 'b');
console.log(myURL.href);
// Print https://example.org/?a=b
const newSearchParams = new URLSearchParams(myURL.searchParams);
// The above is equivalent to
// const newSearchParams = new URLSearchParams(myURL.search);
newSearchParams.append('a', 'c');
console.log(myURL.href);
// Print https://example.org/?a=b
console.log(newSearchParams.toString());
// Print a=b&a=c
// newSearchParams.toString() Is implicitly called
myURL.search = newSearchParams;
console.log(myURL.href);
// Print https://example.org/?a=b&a=c
newSearchParams.delete('a');
console.log(myURL.href);
// Print https://example.org/?a=b&a=c
It has many ways , You can also traverse the parameters as follows :
Format :
urlSearchParams.forEach(fn[, thisArg])
- fn For each name in the query - Value pairs call
- thisArg Calling fn When used as this value
Add :url.searchParams
** Get the URLSearchParams object . **
Let's take an example :
const urlobjct=new URL('https://blog.csdn.net/u011863822?a=A&b=B')
urlobjct.searchParams.forEach(
(value, key) => {
console.log(key,value)
});
also urlSearchParams.sort() Other methods , Look at the name to know what it means , No more demonstrations .
url.format() Method
Looking at the way with the old version seems to be a , But it has more parameters .
Format :
url.format(URL[, options])
- URL WHATWG URL object
- options
- auth If the serialized URL string should contain user name and password , Then for true, Otherwise false. The default value is : true.
- fragment If the serialized URL string should contain fragments , Then for true, Otherwise false. The default value is : true.
- search If the serialized URL string should contain search queries , Then for true, Otherwise false. The default value is : true.
- unicode true If it appears in the host component of the URL string Unicode Characters should be encoded directly instead of Punycode code . The default value is : false.
- return :
demonstration :
import url from 'url';
const myURL = new URL('https://a:[email protected] Test ?abc#foo');
console.log(myURL.href);
// Print https://a:[email protected]/?abc#foo
console.log(myURL.toString());
// Print https://a:[email protected]/?abc#foo
console.log(url.format(myURL, {
fragment: false, unicode: true, auth: false }));
// Print 'https:// Test /?abc'
See the official website for more methods and parameters :http://nodejs.cn/api/url.html#url
querystring modular
querystring.parse Method
The format is as follows :
querystring.parse(str[, sep[, eq[, options]]])
- str URL query string to parse
- sep Substrings used to separate key value pairs in query strings . The default value is : ‘&’.
- eq Substrings used to separate keys and values in the query string . The default value is : ‘=’.
- options
- decodeURIComponent The function used when decoding the percentage encoded characters in the query string . The default value is : querystring.unescape().
- maxKeys Specify the maximum number of keys to resolve . Appoint 0 To remove the count limit of the key . The default value is : 1000.
- querystring.parse() Method to query the URL string (str) Resolves to a set of key value pairs .
Take an example to experience :
const querystring= require('querystring')
const testpara='a=A&b=B'
console.log(querystring.parse(testpara))
querystring.stringify Method
Format :
querystring.stringify(obj[, sep[, eq[, options]]])
- obj Object to serialize as URL query string
- sep Substrings used to separate key value pairs in query strings . The default value is : ‘&’.
- eq Substrings used to separate keys and values in the query string . The default value is : ‘=’.
- options
- encodeURIComponent The function used when converting the unsafe characters of the URL to the percentage encoding in the query string . The default value is :
- querystring.escape().
querystring.stringify() Method by traversing the " own property " From the given obj Generate URL query string .
demonstration :
const querystring= require('querystring')
jsonObject={a:'A',b:'B'}
console.log (querystring.stringify(jsonObject))
Take a look at the example of the official website :
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
// return 'foo=bar&baz=qux&baz=quux&corge='
querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':');
// return 'foo:bar;baz:qux'
querystring.escape(str) and querystring.unescape(str)
querystring.escape()
The method optimizes the given... In a way that is optimized for the specific requirements of the URL query stringstr
Perform URL percentage encoding .querystring.unescape() Method in the given str Perform decoding of URL percentage encoded characters on .
querystring.escape()
Method isquerystring.stringify()
Use , It is not usually used directly . It is mainly exported to allow application code to passquerystring.escape
The percentage encoding implementation assigned to the substitution function to provide substitution .querystring.unescape()
Method isquerystring.parse()
Use , It is not usually used directly . It is mainly exported to allow application code to passquerystring.unescape
Assign an alternative function to provide an alternative decoding implementation . In case of recognition ,querystring.unescape() Method will try to use JavaScript Built in decodeURIComponent() Method to decode . If you fail , You will use a more secure method of the same kind that will not throw errors because of the malformed URL .
demonstration :
const querystring= require('querystring')
const escape_str=querystring.escape('http://example.com/')
console.log(escape_str)
console.log(querystring.unescape(escape_str))
// Of course, it can also be used as sql Simple coding is carried out before and after the statement to prevent simple injection .
边栏推荐
- redis在服务器linux下的启动的相关命令(安装和配置)
- 2022年已过半,得抓紧
- 递归:一维链表和数组
- Recursion: one dimensional linked lists and arrays
- 递归:快速排序,归并排序和堆排序
- Recursion: quick sort, merge sort and heap sort
- Error in compiled file: error: unmapped character encoding GBK
- Téléchargement et installation du client Filezilla
- Ffmpeg download and installation tutorial and introduction
- 可分离债券与可转债
猜你喜欢
2022 P cylinder filling examination content and P cylinder filling practice examination video
SAP UI5 应用开发教程之一百零五 - SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
Pytorch multi card distributed training distributeddataparallel usage
Simple wechat applet development page Jump, data binding, obtaining user information, obtaining user location information
简易版 微信小程序开发之页面跳转、数据绑定、获取用户信息、获取用户位置信息
Ffmpeg download and installation tutorial and introduction
递归:深度优先搜索
MongoDB安装 & 部署
Mongodb replication set [master-slave replication]
Appium自动化测试框架
随机推荐
900w+ data, from 17s to 300ms, how to operate
【全民编程】《软件编程-讲课视频》【零基础入门到实战应用】
105. SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
[DRM] simple analysis of DRM bridge driver call process
The difference between static web pages and dynamic web pages & the difference between Web1.0 and Web2.0 & the difference between get and post
Leetcode: dynamic planning template
释放数据力量的Ceph-尚文网络xUP楠哥
For instruction, uploading pictures and display effect optimization of simple wechat applet development
How to download pytorch? Where can I download pytorch?
FileZilla client download and installation
TCP/IP模型中的重磅嘉宾TCP--尚文网络奎哥
【DRM】DRM bridge驱动调用流程简单分析
Introduction à mongodb
105. Detailed introduction of linkage effect realization of SAP ui5 master detail layout mode
Hutool dynamically adds scheduled tasks
pytorch是什么?pytorch是一个软件吗?
[leetcode question brushing day 34] 540 Unique element in array, 384 Disrupt array, 202 Happy number, 149 Maximum number of points on a line
Docker install and start MySQL service
Mongodb master profile
Shardingsphere dynamic data source