Basic Routing
Routing means deciding what code runs for a given URL path and HTTP method. With the raw http module, you implement routing manually by checking `req.url` and `req.method`.
As an app grows, manual routing becomes repetitive, which is one reason frameworks like Express exist.
Manual routing
Use if/else or switch statements on `req.url` and `req.method` to send different responses for different routes.
Handling 404s
Any URL that doesn't match a known route should return a 404 status so clients know the resource wasn't found.
const http = require('http');
http.createServer((req, res) => {
if (req.url === '/' && req.method === 'GET') {
res.end('Home Page');
} else if (req.url === '/about') {
res.end('About Page');
} else {
res.writeHead(404);
res.end('Not Found');
}
}).listen(3000);Home Page / About Page / Not FoundEach branch checks the URL (and method) to decide the response.
if (req.url === '/api/users' && req.method === 'POST') {
res.end('Creating a user...');
}Creating a user...Routing also considers the HTTP method, not just the path.
Key points
- Routing maps URLs (and methods) to handler logic.
- Manual routing uses conditionals on req.url and req.method.
- Unmatched routes should return a 404 status.
- Frameworks like Express simplify routing significantly.
