Request & Response
Overview
The Request (req) and Response (res) objects represent the entire HTTP transaction. The Request contains everything the user sent you: the URL, the HTTP Method (GET, POST), Headers (Auth Tokens), and the Body (Form data). The Response is the pipeline going back to the user: you set the Status Code (200, 404, 500), configure security Headers (CORS), and finally stream the physical payload (JSON, HTML) back to their browser.
Syntax
const http = require('http');
const server = http.createServer((req, res) => {
// --- 1. INSPECTING THE REQUEST (req) ---
console.log(req.method); // 'GET', 'POST', 'DELETE'
console.log(req.url); // '/api/users?sort=asc'
console.log(req.headers['user-agent']); // Identifies the browser!
// --- 2. CRAFTING THE RESPONSE (res) ---
// A standard JSON API response
const payload = JSON.stringify({ error: false, message: "Success" });
// Set headers manually
res.setHeader('Content-Type', 'application/json');
res.setHeader('X-Powered-By', 'Node.js');
// Set the status code and end the stream!
res.statusCode = 200;
res.end(payload);
});Common Pitfalls
- Trying to send headers AFTER you have already sent the body. HTTP protocol strictly dictates that Headers must be sent first, followed by a blank line, followed by the Body. If you call
res.write('Hello')and then try to callres.setHeader(...), Node will throw a fatalERR_HTTP_HEADERS_SENTcrash. - Assuming
req.bodyexists natively. In raw Node.js, the Request body does NOT exist as a parsed object. Because the request is a Stream, the body comes in as raw binary chunks. You have to manually listen toreq.on('data')and concatenate the chunks to read a JSON payload (Express automates this).
Interview Questions
res.setHeader() and res.writeHead()?setHeader() allows you to queue up multiple headers individually over multiple lines of code. writeHead() mathematically finalizing the headers, writing the Status Code and all queued headers into the TCP socket instantly, preventing any further header modifications.
Real-World Example
Extracting a Bearer Token (JWT) from the raw Request Headers.
const authHeader = req.headers['authorization'];
if (!authHeader || !authHeader.startsWith('Bearer ')) {
res.statusCode = 401; // Unauthorized
return res.end('Missing or invalid token.');
}
const token = authHeader.split(' ')[1]; // Extracts the actual JWT string
console.log("Token received:", token);Check Your Knowledge
Test your understanding of Request & Response with these quick questions.