Understanding raw HTTP server handling in Node.js reveals how Express and modern frameworks operate under the hood.
⊞Code Example
const http = require('http');
const server = http.createServer((req, res) => {
const { url, method } = req;
// Setting response headers
res.setHeader('Content-Type', 'application/json');
if (url === '/api/health' && method === 'GET') {
res.writeHead(200);
res.end(JSON.stringify({ status: 'ok', uptime: process.uptime() }));
} else {
res.writeHead(404);
res.end(JSON.stringify({ error: 'Endpoint Not Found' }));
}
});
const PORT = 5000;
server.listen(PORT, () => {
console.log(`Server listening on http://localhost:${PORT}`);
});
