Skip to content
Justice Tech School

Query Strings

Parse the query with URLSearchParams from req.url.

Example
const http = require("http");
const s = http.createServer((req, res) => {
  const u = new URL(req.url, "http://localhost");
  res.end("hello " + (u.searchParams.get("name") ?? "guest"));
}).listen(0, async () => {
  const base = "http://localhost:" + s.address().port;
  console.log(await (await fetch(base + "/?name=Ada")).text(), await (await fetch(base)).text());
  s.close();
});

Result

hello Ada hello guest

Exercise

Read a param.

searchParams.("name")

Quiz Test

What does ?? do here?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.