Beginner · APIs and request handling · topic 8 of 54 · 25 min
Routing: sending each request to the right code
Explanation
What a router does
A route is one pair of a method and a path pattern, joined to a handler. A handler is the function that does the work for that route. A router is the code that takes each request, finds the matching route and calls its handler.
A route table
A route table is a simple list of routes. The router checks them from top to bottom and uses the first one that matches.
const routes = [
{ method: 'GET', pattern: '/products', handler: () => 'list products' },
{ method: 'POST', pattern: '/products', handler: () => 'create product' },
{ method: 'GET', pattern: '/products/:id', handler: () => 'read one product' },
];
for (const r of routes) console.log(r.method.padEnd(5), r.pattern);Path parameters
A path parameter is a part of the pattern that starts with a colon, like :id in /products/:id. It matches any value in that place, and the router saves the value under that name. For /products/42, the params are { id: "42" }.
- Split the pattern and the path on "/" and drop empty parts.
- If they have a different number of parts, it is not a match.
- Compare part by part. A pattern part starting with ":" matches anything; save the value under its name.
- Any other pattern part must be exactly equal to the path part.
- If every part matched, return the saved params. Otherwise return null.
function splitPath(path) {
return path.split('/').filter(Boolean);
}
console.log(splitPath('/users/42/orders')); // [ 'users', '42', 'orders' ]
console.log(splitPath('/users/42/')); // [ 'users', '42' ]
console.log(splitPath('/')); // []Query strings
The query string is not part of the route. GET /products?category=rice and GET /products both go to the same route. The handler then reads the options with URLSearchParams.
const raw = '/products?category=rice&maxPrice=200';
const [path, queryText] = raw.split('?');
const query = new URLSearchParams(queryText);
console.log(path); // /products
console.log(query.get('category')); // rice
console.log(Number(query.get('maxPrice'))); // 200
console.log(query.get('sort')); // nullWatch the lesson
Routing: sending each request to the right code · 1/6
Routing means choosing which function handles a request, by looking at its method and path.
Prefer a video by a teacher? Find free videos on “how routing works in backend express route parameters tutorial” on YouTube ↗
In real life: How Express does routing
Express is the most used Node.js backend framework. Its routes look exactly like our table: a method, a pattern with :params, and a handler. Express fills req.params from the path and req.query from the query string, so the handler gets them ready to use. You will build this for real in module 3.
// runs on a server with Node.js and Express installed
const express = require('express');
const app = express();
app.get('/products/:id', (req, res) => {
const id = Number(req.params.id);
res.json({ id, currency: req.query.currency || 'INR' });
});
app.listen(3000);Practice (0/3 done)
Write a function splitPath(path) that returns the parts of a path between slashes, without empty parts. "/users/42/" gives ["users", "42"] and "/" gives [].
Write a function matchRoute(pattern, path). If the path fits the pattern, return an object of path parameters (an empty object {} when the pattern has none). If it does not fit, return null. Example: matchRoute("/users/:id", "/users/42") gives { id: "42" }.
Build a tiny router. matchRoute is given. Write route(routes, request): find the first route whose method equals request.method and whose pattern matches request.path. Call its handler with { ...request, params } and return what it returns. If no route matches, return { status: 404, body: "Not found" }.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.