Node.js ยท Chapter 15 of 43

URL & Query Strings

The `url` module (and the global `URL` class) helps parse URLs into their parts: protocol, host, pathname, and query string parameters.

Query strings carry extra data in a URL after a `?`, like `?search=node&page=2`, and are commonly used for filtering or pagination.

Parsing URLs

The `URL` class parses a full URL string into properties like `.pathname`, `.searchParams`, and `.hostname`.

Reading query parameters

`url.searchParams.get('key')` retrieves a specific query parameter's value.

Example 1 (javascript)
const { URL } = require('url');
const myUrl = new URL('http://localhost:3000/search?term=node&page=2');
console.log(myUrl.pathname);
console.log(myUrl.searchParams.get('term'));
Output
/search
node

The URL is parsed into pathname and accessible query parameters.

Example 2 (javascript)
for (const [key, value] of myUrl.searchParams) {
  console.log(key, value);
}
Output
term node
page 2

searchParams is iterable, letting you loop over all query parameters.

Key points

  • The URL class parses full URLs into structured parts.
  • searchParams.get() reads a specific query parameter.
  • Query strings appear after a '?' in a URL.
  • searchParams is iterable for looping over all params.
๐Ÿ’ก Note: In Express, query strings are automatically parsed into `req.query`.

๐Ÿ“ Quick Quiz

1. What class parses full URLs in Node.js?

2. Which method reads one query parameter's value?

3. In Express, where do parsed query strings appear?