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.

1
2
3
4
5
6
7
const http = require('http');

http
  .createServer((req, res) => {
    res.end('hello world');
  })
  .listen(8080, '127.0.0.1');

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.

1
const url = '/api?a=1&b=2&c=ccc'; // 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.

1
2
3
4
5
new URL('/api?a=1'); // Uncaught TypeError: Failed to construct 'URL': Invalid URL
new URL('//www.qq.com'); // Invalid URL 解析错误
new URL('//www.qq.com', 'htts://example.com'); // 正确解析,origin: https://www.xiabingbao.com
new URL('http://www.qq.com', 'https://example.com'); // 正确解析,还是使用自己的http协议, http://www.qq.com
new URL('/api?a=1', 'https://example.com'); // 正确解析,href: https://example.com/api?a=1

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const uu = new URL('/api?a=1&b=2&c=ccc', 'https://example.com');
const { searchParams } = uu;
searchParams.get('a'); // '1'
searchParams.get('b'); // '2'
searchParams.get('c'); // 'ccc'
searchParams.get('d'); // null
searchParams.has('a'); // 是否有参数a
[...searchParams.values()]; // 所有数值的集合 ['1', '2', 'ccc']
[...searchParams.keys()]; // 所有key的集合['a', 'b', 'c']

searchParams.forEach(console.log); // 循环所有的数据
searchParams.getAll('a'); // 获取所有的参数a ['1']

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.

1
2
3
4
5
const obj = {};
for (let [key, value] of searchParams) {
  obj[key] = value;
}
console.log(obj);

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?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const http = require('http');

http
  .createServer((req, res) => {
    const { searchParams } = new URL(req.url, 'https://example.com');
    const username = searchParams.get('username') || 'wenzi';

    res.end(`${username}, hello world\n`);
  })
  .listen(8080, '127.0.0.1');

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.