๐ HTTP Servers
http module lets you create web servers in Node.js. Clients send HTTP requests to your server, and your server sends back HTTP responses. This chapter covers creating a basic HTTP server, handling requests, sending responses, parsing URLs, and routing requests to different handlers.
๐ก HTTP Basics
HTTP is a request-response protocol:
Request
Client sends: method, URL, headers, body.
Response
Server sends: status code, headers, body.
Methods
GET (read), POST (create), PUT (update), DELETE (remove).
Status Codes
200 (OK), 404 (Not Found), 500 (Error), etc.
๐๏ธ Creating a Basic Server
const http = require('http'); const server = http.createServer((req, res) => { // req: the request object // res: the response object res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!'); }); server.listen(3000, 'localhost', () => { console.log('Server running at http://localhost:3000/'); });
Run with node server.js, then visit http://localhost:3000 in your browser.
๐ฅ The Request Object
The req object contains information about the client's request:
const server = http.createServer((req, res) => { console.log('Method:', req.method); // GET, POST, etc. console.log('URL:', req.url); // /path?query=value console.log('Headers:', req.headers); // {host, user-agent, ...} res.end('OK'); });
๐ค The Response Object
Use the res object to send a response:
// Set status code res.statusCode = 200; // Set headers res.setHeader('Content-Type', 'text/html'); res.setHeader('X-Custom-Header', 'value'); // Write body res.write('Hello
'); res.write('World
'); // End response (required!) res.end();
๐ฃ๏ธ Routing Requests
Handle different URLs differently:
const server = http.createServer((req, res) => { if (req.url === '/' && req.method === 'GET') { res.statusCode = 200; res.end('Home Page'); } else if (req.url === '/about') { res.statusCode = 200; res.end('About Page'); } else { res.statusCode = 404; res.end('Not Found'); } });
๐ Parsing Requests
Parse URL and Query Parameters
const { URL } = require('url'); const server = http.createServer((req, res) => { const url = new URL(req.url, `http://${req.headers.host}`); console.log('Pathname:', url.pathname); // /search console.log('Query:', url.search); // ?q=node const query = url.searchParams.get('q'); console.log('Search query:', query); // node res.end('OK'); });
๐ JSON Responses
const server = http.createServer((req, res) => { const data = { message: 'Hello, World!', timestamp: new Date() }; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(data)); });
๐ฎ Handling POST Requests
const server = http.createServer(async (req, res) => { if (req.method === 'POST') { let body = ''; // Collect request body req.on('data', chunk => { body += chunk.toString(); }); // Process when finished req.on('end', () => { const data = JSON.parse(body); console.log('Received:', data); res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ success: true })); }); } });
๐ Serving Static Files
const fs = require('fs'); const path = require('path'); const server = http.createServer(async (req, res) => { const filePath = path.join(__dirname, 'public', req.url); try { const data = await fs.promises.readFile(filePath); res.statusCode = 200; res.end(data); } catch (error) { res.statusCode = 404; res.end('Not Found'); } });
๐ข Common Status Codes
2xx Success
200 OK, 201 Created, 204 No Content
3xx Redirect
301 Moved, 302 Found, 304 Not Modified
4xx Client Error
400 Bad Request, 401 Unauthorized, 404 Not Found
5xx Server Error
500 Internal Error, 502 Bad Gateway, 503 Unavailable
๐ป Coding Challenges
Challenge 1: Basic HTTP Server
Create a server that responds to /, /about, /api/users routes with different responses.
Goal: Learn server creation and basic routing.
Challenge 2: JSON API
Create a server that accepts GET/POST requests and responds with JSON data.
Goal: Handle requests and build a simple API.
Challenge 3: Serve Static Files
Create a server that serves HTML, CSS, and image files from a public directory.
Goal: Understand content types and static file serving.
1. Always end responses: Call res.end() or data won't be sent.
2. Set correct content types: HTML, JSON, images need different MIME types.
3. Handle errors: Files might not exist, requests might be malformed.
4. Use Express later: For production, use frameworks like Express.js (we'll cover in exp1).
๐ฏ What's Next
You've created HTTP servers with Node.js! We'll explore more advanced topics, and soon move to Express.js โ a powerful web framework that makes building servers much easier.