HTTP Server
Building web servers with Node's built-in http module
Skills taught: node.http-createserver, node.request-response, node.routing, node.json-api
Creating an HTTP server
const http = require('http');
const server = http.createServer((req, res) => {
// req.method: 'GET', 'POST', 'PUT', 'DELETE'
// req.url: '/api/users', '/about', '/'
console.log(`${req.method} ${req.url}`);
// Simple routing
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello from Node.js!</h1>');
} else if (req.url === '/api/status' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', uptime: process.uptime?.() || 0 }));
} else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not found' }));
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
const http = require('http');
const users = [
{ id: 1, name: 'Alice', role: 'admin' },
{ id: 2, name: 'Bob', role: 'user' },
];
function jsonResponse(res, statusCode, data) {
res.writeHead(statusCode, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
});
res.end(JSON.stringify(data, null, 2));
}
const server = http.createServer(async (req, res) => {
const { method, url } = req;
if (url === '/users' && method === 'GET') {
return jsonResponse(res, 200, users);
}
if (url === '/users' && method === 'POST') {
let body = '';
req.on('data', chunk => { body += chunk; });
req.on('end', () => {
try {
const newUser = JSON.parse(body);
newUser.id = users.length + 1;
users.push(newUser);
jsonResponse(res, 201, newUser);
} catch {
jsonResponse(res, 400, { error: 'Invalid JSON' });
}
});
return;
}
jsonResponse(res, 404, { error: 'Not found' });
});
server.listen(3000, () => console.log('API ready on :3000'));
Tip: In real Node.js, reading the request body requires collecting stream chunks: `let body=''; req.on('data', c => body+=c); req.on('end', () => JSON.parse(body))`. The sandbox simplifies this by providing req.body as a string directly.
Frequently Asked Questions
Why do most Node.js projects use Express instead of the raw http module?
The raw http module handles every detail manually: routing (if/else on req.url), body parsing (stream chunks), content negotiation, error handling, middleware chains. Express adds routing (app.get('/path', handler)), automatic body parsing (express.json()), middleware (app.use()), and cleaner error handling — saving hundreds of lines of boilerplate for every real API.