π http Module - Simplified Web Communication
HTTP (HyperText Transfer Protocol) is the foundation of data communication on the World Wide Web. Itβs an application-layer protocol that defines how messages are formatted and transmitted between clients (like your web browser) and servers.
Key characteristics of HTTP include:
- Client-Server Model: A client initiates a request for a resource, and a server processes it and sends back a response.
- Stateless: Each request is an independent transaction. The server does not store any information about previous requests from the same client. (State is managed at a higher level using things like cookies and sessions).
- Built on TCP: HTTP uses the reliable, connection-oriented TCP protocol to ensure that requests and responses are delivered correctly and in order.
βοΈ The Core http Workflow
Handling an HTTP request in Node.js follows a clear, event-driven workflow.
- Create a Server: You start by calling
http.createServer(). This creates a server object that is anEventEmitter. - Listen for Connections: You call
server.listen(PORT)to bind the server to a network port and tell it to start accepting incoming connections. - Handle the Request: When a client sends a request, the callback function passed to
createServeris executed. This function receives two crucial objects:request(req) andresponse(res). - Parse the Request: Your code inspects the
requestobjectβspecifically itsreq.url,req.method, andreq.headerspropertiesβto determine what the client is asking for. ForPOSTorPUTrequests, you read the incoming data from thereqobject, which is a Readable Stream. - Build the Response: Based on the request, you use the
responseobject to construct the reply. This involves:- Setting the status code and headers using
res.writeHead(statusCode, headers). TheContent-Typeheader is essential here. - Writing the response body. Since the
resobject is a Writable Stream, you can send data withres.write(data).
- Setting the status code and headers using
- Send the Response: You call
res.end()to signal that the response is complete and should be sent to the client. This finalizes the transaction.
π HTTP Headers
Headers are key-value pairs of metadata sent with every HTTP request and response. They provide essential information about the message, the client, the server, and how the connection should be handled.
Request Headers (Client β Server)
These are sent by the client to give the server more context about the request.
Host: The domain name of the server (e.g.,www.google.com).User-Agent: Information about the client making the request (e.g.,Mozilla/5.0 ... Chrome/115.0.0.0 ...).Accept: The content types the client can understand (e.g.,application/json,text/html).Content-Type: The MIME type of the body of the request (e.g.,application/jsonwhen sending JSON data with aPOSTrequest).Authorization: Carries credentials for authenticating a client with a server.
Response Headers (Server β Client)
These are sent by the server to give the client information about the response.
Content-Type: The MIME type of the response body (e.g.,text/htmlfor a web page,application/jsonfor API data). This is one of the most important headers to set.Content-Length: The size of the response body in bytes.Status: A status line indicating the outcome (e.g.,200 OK,404 Not Found). This is sent viares.writeHead().Location: Used for URL redirection (sent with a301or302status code).Set-Cookie: Instructs the client to save a cookie.
π·οΈ HTTP Methods
HTTP Methods, or βverbs,β indicate the desired action to be performed on a resource.
GET: Retrieve data from a resource. This is the most common method, used when you navigate to a website. It should be βsafeβ (no side effects).POST: Submit data to a resource to be processed, often resulting in a new resource being created (e.g., creating a new user account or submitting a form).PUT: Replace an existing resource with the data provided in the request body.DELETE: Delete a specified resource.PATCH: Apply partial modifications to a resource.HEAD: Same asGET, but it only asks for the headers, not the response body. Useful for checking if a resource exists before downloading it.OPTIONS: Describes the communication options (e.g., which methods are allowed) for the target resource.
π» Example: A Simple API Server
This example creates a basic web server using the http module that handles different URLs and methods.
const http = require("http");
const PORT = 4000;
const server = http.createServer((req, res) => {
// The 'req' object is a Readable Stream.
// The 'res' object is a Writable Stream.
// --- ROUTING ---
if (req.method === "GET" && req.url === "/") {
// Set status code and content type header
res.writeHead(200, { "Content-Type": "text/html" });
// Send the response body
res.end("<h1>Welcome to the Homepage!</h1>");
} else if (req.method === "GET" && req.url === "/about") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "This is the about page." }));
} else if (req.method === "POST" && req.url === "/submit") {
let body = [];
// Read the incoming request body (stream)
req.on("data", (chunk) => {
body.push(chunk);
});
// When the request stream ends...
req.on("end", () => {
const parsedBody = Buffer.concat(body).toString();
console.log("Received data:", parsedBody);
res.writeHead(201, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "success", data: parsedBody }));
});
} else {
// Handle 404 Not Found
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("404 Not Found");
}
});
server.listen(PORT, () => {
console.log(`Server listening on http://localhost:${PORT}`);
});