HTTP Servers
🌐 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
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:
📤 The Response Object
Use the res object to send a response:
Hello
'); res.write('World
'); // End response (required!) res.end();🛣️ Routing Requests
Handle different URLs differently:
🔍 Parsing Requests
Parse URL and Query Parameters
📋 JSON Responses
📮 Handling POST Requests
📂 Serving Static Files
🔢 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.