Basic Routing
Send different responses based on the URL and method.
Syntax
if (req.url === '/about') { ... }Routing means responding differently depending on the request's URL and method. With the plain http module you do this by checking req.url and req.method.
A simple router
Compare the URL against known paths and send the matching response. If nothing matches, return a 404.
Example
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/' ) {
res.end('Home page');
} else if (req.url === '/about') {
res.end('About page');
} else {
res.statusCode = 404;
res.end('Not found');
}
});
server.listen(3000);When to use it
- A REST API built with only the `http` module uses a switch on `req.method + req.url` to dispatch `/users` GET and POST requests to different handlers.
- A webhook server routes `POST /github` and `POST /stripe` to different processing functions by matching the request URL.
- A developer builds a tiny router helper that supports URL parameters like `/users/:id` to avoid framework dependencies for a small internal service.
More examples
Basic URL routing with if/else
Routes requests by checking `req.url` and `req.method` with simple conditionals -- the foundation of any router.
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);Method + path dispatch table
Uses an object as a dispatch table keyed by `'METHOD /path'` -- scales more cleanly than nested if/else.
const routes = {
'GET /': (req, res) => res.end('GET /'),
'GET /health': (req, res) => res.end('{"status":"ok"}'),
'POST /data': (req, res) => res.end('Data received'),
};
http.createServer((req, res) => {
const key = `${req.method} ${req.url}`;
const handler = routes[key];
if (handler) handler(req, res);
else { res.writeHead(404); res.end(); }
}).listen(3000);Extract URL parameters manually
Uses the built-in `URL` class to parse the pathname and query-string parameters from the request URL.
const http = require('http');
const { URL } = require('url');
http.createServer((req, res) => {
const u = new URL(req.url, 'http://localhost');
const id = u.pathname.split('/')[2]; // '/users/42' -> '42'
const q = u.searchParams.get('filter');
res.end(JSON.stringify({ id, filter: q }));
}).listen(3000);
// curl 'http://localhost:3000/users/42?filter=active'
Discussion