HTTP Module: Creating a Basic Server
Learn to create HTTP servers in Node.js without frameworks. Understand the foundation of web servers.
HTTP Module: Creating a Basic Server
Before Express, there's the http module. Understanding it helps you grasp how servers work.
Basic Server
```javascript const http = require('http');
const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World!'); });
server.listen(3000, () => { console.log('Server running at http://localhost:3000'); }); ```
Request Object (req)
```javascript const server = http.createServer((req, res) => { console.log(req.method); // GET, POST, etc. console.log(req.url); // /path?query=value console.log(req.headers); // { host: 'localhost', ... } res.end('Request received'); }); ```
Response Object (res)
```javascript const server = http.createServer((req, res) => { // Set status code res.statusCode = 200; // Set headers res.setHeader('Content-Type', 'application/json'); res.setHeader('X-Custom-Header', 'MyValue'); // Or all at once res.writeHead(200, { 'Content-Type': 'application/json', 'X-Custom-Header': 'MyValue' }); // Send response res.end(JSON.stringify({ message: 'Hello' })); }); ```
Simple Router
```javascript const http = require('http');
const server = http.createServer((req, res) => { const { method, url } = req; if (method === 'GET' && url === '/') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<h1>Home Page</h1>'); } else if (method === 'GET' && url === '/api/users') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify([{ id: 1, name: 'Alice' }])); } else if (method === 'GET' && url === '/about') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<h1>About Page</h1>'); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not Found'); } });
server.listen(3000); ```
Handling POST Data
```javascript const server = http.createServer((req, res) => { if (req.method === 'POST' && req.url === '/api/users') { let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', () => { const user = JSON.parse(body); console.log('Received:', user); res.writeHead(201, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ success: true, user })); }); } }); ```
Serving Static Files
```javascript const http = require('http'); const fs = require('fs'); const path = require('path');
const server = http.createServer((req, res) => { let filePath = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url); const ext = path.extname(filePath); const contentTypes = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.json': 'application/json' }; fs.readFile(filePath, (err, content) => { if (err) { res.writeHead(404); res.end('File not found'); } else { res.writeHead(200, { 'Content-Type': contentTypes[ext] || 'text/plain' }); res.end(content); } }); }); ```
Key Takeaway
The http module is Node.js's built-in way to create servers. It's low-level but teaches you the fundamentals. Express and other frameworks build on top of this. Know http basics, then use frameworks for real projects.