UNDERSTANDING REQUEST AND RESPONSE OBJECTS

WHAT IS A REQUEST?

In web development and HTTP communication, a request is the data package sent by a client (usually a web browser or app) to a server, asking for a specific resource or service. It initiates interaction with the server, such as fetching a webpage, submitting form data, or calling an API endpoint. In Node.js, the request object (req) gives you access to all this information so you can handle it programmatically.

Key Components of an HTTP Request

  • Method– Specifies the action type like GET, POST, PUT, DELETE, etc.
  • URL/Path– Identifies the resource being requested (e.g., /home, /api/user).
  • Headers– Metadata like content type (Content-Type: application/json), authentication tokens, or user-agent details.
  • Query Parameters– Key–value pairs appended to the URL, like ?id=123.
  • Body (optional)– Payload included with methods like POST or PUT, often used to send data like JSON or form entries.

EXAMPLE-

POST /login HTTP/1.1
Host: example.com
Content-Type: application/json

{
“username”: “JAMES FORD”,
“password”: “Network123”
}

WHAT IS A RESPONSE?

In web development, a response is the server’s reply to a client’s HTTP request. Once the client (typically a browser or an application) sends a request to the server for some resource or action, the server processes it and then sends back a response that includes status information and possibly content. In Node.js, you use the res object to construct and send this response. The server decides the content based on the route and logic, enabling communication between systems.

Key Components of an HTTP Response

  • Status Line– Includes a status code (e.g. 200 OK, 404 Not Found) indicating the outcome of the request.
  • Headers– Metadata about the response, such as content type (Content-Type: application/json), caching rules, and cookies.
  • Body (optional)– The actual data returned, could be an HTML page, JSON payload, image file, or plain text, depending on the request and server logic.

EXAMPLE-

HTTP/1.1 200 OK
Content-Type: text/plain

Hello, JAMES FORD! Your request was successfully processed.

REQUEST AND RESPONSE OBJECTS

In Node.js, especially when working with the built-in http module, the request (req) and response (res) objects are two core components passed to the callback in http.createServer().

1. Request Object (req)– The req object represents the incoming HTTP request from the client.

  • Key Properties:
    • req.url – Path requested by the client.
    • req.method – HTTP method used (e.g., GET, POST).
    • req.headers – Object containing HTTP headers.
    • req.on('data') – Used to read incoming data chunks (for POST/PUT).
    • req.on('end') – Signals that request body has been fully received.

EXAMPLE-

console.log(req.method); // ‘GET’
console.log(req.url); // ‘/home’

2. Response Object (res)– The res object is used to send back data to the client.

  • Key Methods:
    • res.writeHead(statusCode, headers) – Sets status and headers.
    • res.write(data) – Writes chunks to the response body.
    • res.end([data]) – Signals end of the response and optionally sends final data.

EXAMPLE-

res.writeHead(200, { ‘Content-Type’: ‘text/plain’ });
res.end(‘Hello from Node.js HTTP server’);

THIS IS A EXAMPLE SERVER WITH FULL FLOW-

const http = require(‘http’);

const server = http.createServer((req, res) => {
console.log(Method: ${req.method}, URL: ${req.url});

res.writeHead(200, { ‘Content-Type’: ‘text/plain’ });
res.end(‘Request received and response sent.’);
});

server.listen(3000, () => {
console.log(‘Server running at http://localhost:3000’);
});

Explanation for the above code-

  • Uses req.url and req.method to manually match request routes.
  • You define a series of conditional branches (if, else if) for each endpoint.
  • If no match is found, the server defaults to a 404 Not Found response.
  • This pattern helps you understand the underlying logic before switching to frameworks.

BARE METAL ROUTING-

Bare-metal routing refers to manually implementing routing logic using low-level constructs, typically without the aid of web frameworks like Express, Koa, or Fastify. In the context of Node.js, it means handling routing through conditional checks (if, switch, etc.) using the built-in http module, giving developers full control over URL parsing, method matching, and response generation. Bare-metal routing strips away convenience in favor of explicit control, useful when performance, dependency minimization, or architectural clarity are priorities.

Characteristics of Bare-Metal Routing

  • Direct Use of http.createServer()– No abstraction layers, requests are handled using raw Node.js syntax.
  • Conditional Matching for Path and Method– Routes are differentiated manually using req.url and req.method.
  • No Middleware System– Every task (like parsing bodies or handling CORS) must be coded from scratch or supplemented with minimal modules.
  • Ideal for Learning or Lightweight Services– Good for understanding HTTP fundamentals or building simple tools with tight resource constraints.

EXAMPLE CODE-

const http = require(‘http’);

const server = http.createServer((req, res) => {
const { url, method } = req;

if (url === ‘/hello’ && method === ‘GET’) {
res.writeHead(200, { ‘Content-Type’: ‘text/plain’ });
res.end(‘Hello from bare-metal routing’);
} else {
res.writeHead(404, { ‘Content-Type’: ‘text/plain’ });
res.end(‘Not Found’);
}
});

server.listen(3000);

Pros of bare-metal routing-

  1. Fine-Grained Control– You can dictate exactly how each route behaves without abstract layers. This is ideal for understanding the raw mechanics of HTTP handling and customizing behavior down to individual headers and logic flows.
  2. Minimal Dependencies– Bare-metal routing uses only Node’s built-in http module, keeping your project lightweight and reducing external dependencies, which is advantageous for security audits or low-footprint deployments.
  3. Educational Value– Implementing routing manually strengthens your grasp of the HTTP lifecycle, request–response structure, and event-driven programming in Node.js. It’s a great foundation before adopting frameworks like Express.

Cons of bare-metal routing-

  1. Lack of Scalability– As your project grows, managing hundreds of conditional branches becomes unmanageable. Frameworks offer cleaner, modular abstractions for route organization and middleware chaining.
  2. No Built-In Middleware Support– Tasks like parsing JSON, handling cookies, or managing sessions require custom implementation or manual integration of helper libraries, leading to more boilerplate code.
  3. Harder to Maintain and Extend– Without route grouping, middleware layering, or error-handling conventions, making changes or onboarding new developers is slower and more error-prone.