Skip to Content
πŸŽ‰ Welcome to my notes πŸŽ‰
Node.jsNetworking🌍 http Module - Simplified Web Communication

🌍 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.

  1. Create a Server: You start by calling http.createServer(). This creates a server object that is an EventEmitter.
  2. Listen for Connections: You call server.listen(PORT) to bind the server to a network port and tell it to start accepting incoming connections.
  3. Handle the Request: When a client sends a request, the callback function passed to createServer is executed. This function receives two crucial objects: request (req) and response (res).
  4. Parse the Request: Your code inspects the request objectβ€”specifically its req.url, req.method, and req.headers propertiesβ€”to determine what the client is asking for. For POST or PUT requests, you read the incoming data from the req object, which is a Readable Stream.
  5. Build the Response: Based on the request, you use the response object to construct the reply. This involves:
    • Setting the status code and headers using res.writeHead(statusCode, headers). The Content-Type header is essential here.
    • Writing the response body. Since the res object is a Writable Stream, you can send data with res.write(data).
  6. 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/json when sending JSON data with a POST request).
  • 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/html for a web page, application/json for 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 via res.writeHead().
  • Location: Used for URL redirection (sent with a 301 or 302 status 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 as GET, 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.

server.js
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}`); });
Last updated on