Routing
What is routing?
Section titled “What is routing?”Routing is the process of deciding which piece of code handles a given HTTP request. The decision is based on two properties of the request:
req.method— the HTTP verb:GET,POST,PUT,DELETE, etc.req.url— the path (and optional query string):/users,/users/42,/search?q=node
Node’s built-in server gives you both. You write the logic that maps them to handlers.
Manual routing with if/else
Section titled “Manual routing with if/else”The simplest router is a chain of if statements:
Needs the Node.js runtime — open in StackBlitz to run.
Parsing the URL with the URL class
Section titled “Parsing the URL with the URL class”When URLs contain path parameters or query strings, use Node’s global URL constructor to parse them cleanly. Pass req.url as the first argument and a fake base as the second:
Needs the Node.js runtime — open in StackBlitz to run.
A tiny router object
Section titled “A tiny router object”Once you have more than a few routes, extract them into a router map. This is exactly the pattern that Express uses internally:
Needs the Node.js runtime — open in StackBlitz to run.