How do you parse the parameters in the request URL in the native http service of nodejs? The official url.parse()
method is no longer recommended, so what method should I use?
In nodejs, the url.parse
method was previously recommended for parsing parameters, but this method is no longer recommended, and now the recommended API is the WHATWG URL.
Since all the methods found on the web are still the same as before, here is a record of how to use the URL class or URLSearchParams class to get the requested parameters in nodejs.
1. Create a service
We start by creating a simple http service with http.createServer
.
It’s easy to start a service in nodejs.
2. Using URLs
Before we get to the parameters, let’s explain how to use URL
.
URLs are supported in both browsers and nodejs, and in nodejs they were added in version 8.0.0.
In the nodejs http service, we can get the path of the request and the arguments it carries via req.url
.
|
|
2.1 Parsing an url
Then we can parse the url by using the URL class, but note that.
If only one parameter is passed to the URL, this url must be an absolute address, i.e., it needs to carry the protocol, such as http://, https://, file://, etc.; if we are not sure whether the first parameter carries the protocol and host information, we can use the second parameter to supplement it.
When the first parameter contains protocol and host, it is used directly; otherwise the information in the second parameter will be used for complementation.
Let’s test a few.
|
|
You can see that if the first parameter is an absolute address, it will be used directly; otherwise, the second parameter will be concatenated with the first parameter and then parsed.
2.2 Parsing parameters
So how do you parse the parameters? The parameters are already in the searchParams
property of the instance, which is also an instance of URLSearchParams.
|
|
The keys()
, values()
, entries()
and so on in searchParams are iterator methods. You can’t get the data of a json structure directly, so how do you construct it?
2.3 How to serialize parameters
There is no direct way to get them here, we need to implement them ourselves by iterator loop, for knowledge about iterators, please refer to https://es6.ruanyifeng.com/#docs/iterator.
This will give you an object type of data.
3. Use in nodejs
We’ve seen how to use URLs above, how do we use them in nodejs?
Parsing is complete.
When we make a request to the interface with the username parameter, the interface will return the corresponding data, which means the parsing is successful.