Node.js ยท Chapter 14 of 43

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.

Example 1 (javascript)
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);
Output
Home Page / About Page / Not Found

Each branch checks the URL (and method) to decide the response.

Example 2 (javascript)
if (req.url === '/api/users' && req.method === 'POST') {
  res.end('Creating a user...');
}
Output
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.
๐Ÿ’ก Note: Manual routing works for small apps but doesn't scale well โ€” that's what Express solves.

๐Ÿ“ Quick Quiz

1. What two request properties are usually checked for routing?

2. What status code should an unmatched route return?

3. Why do frameworks like Express exist?