HTTP Module (Core Native Server)
The explicit foundation of Express.js. Learn to organically create web servers, carefully handle HTTP requests and efficiently process structural responses.
What is the HTTP Module?
Definition: The standard HTTP module native directly in Node.js structurally allows you to dynamically create a functional web server manually handling all basic incoming HTTP connections and correctly triggering sequential responses natively.
Key Engineering Concept
This is the underlying fundamental execution foundation powering Express.js infrastructure.
- Everything Express automatically manages essentially wraps native logic surrounding:
http.createServer()
Creating Your First Server Core
import http from 'http';
const server = http.createServer((req, res) => {
res.end("Hello World");
});
server.listen(3000, () => {
console.log("Server engine running on port 3000");
});Execution Operation Breakdown
- The local development server process is intrinsically created.
- It establishes a permanent listening sequence tied strictly to port
3000. - For essentially every mapped incoming URL request object → The designated fallback callback code executes completely.
Processing Variables: req and res
📥 req (Request Object)
Contains distinctly sourced metadata payloads originating from the executing client:
- URL Path → req.url
- Verb Method → req.method
- Data Headers → req.headers
📤 res (Response Object)
Employed systematically to resolve and transmit compiled data payloads successfully back:
- res.write(data)
- res.end(data)
- res.setHeader(...)
const server = http.createServer((req, res) => {
// Extrapolate payload data dynamically
console.log(req.method, req.url);
// Sequentially assemble final payload output
res.write("Hello ");
res.end("World");
});Fundamental Path Routing (Manual)
Without Defined Target Routing
Every distinctly mapped request logically renders universally identical global outcome responses indiscriminately.
With Manual Execution Routing
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.end("Home Page");
} else if (req.url === "/about") {
res.end("About Page");
} else {
res.statusCode = 404;
res.end("Not Found");
}
});switch-case chains force immense repetitive overhead natively cleanly abstracted completely away later employing external frameworks primarily resolving scaling patterns dynamically using Express router logic integrations.Parsing Request Target HTTP Methods
if (req.method === "GET") {
res.end("Process GET operation");
} else if (req.method === "POST") {
res.end("Process POST payload operation");
}| Operational Focus Method | Integration Meaning Specification |
|---|---|
| GET | Safely securely request and fetch server configuration processing / payload data. |
| POST | Securely transmit creation or internal processing variables to the backend execution. |
| PUT | Commit update modifiers explicitly overwriting previous structural assignments. |
| DELETE | Command system destruct parameters directly cleanly resolving logic entirely. |
Formatting JSON Responses
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({
name: "Shivam",
role: "Developer"
}));
});JSON.stringify) prior to sending output bytes payload across generic stream arrays.Parsing Request Body Dynamics (POST)
const server = http.createServer((req, res) => {
if (req.method === "POST") {
let body = "";
req.on("data", chunk => {
body += chunk.toString();
});
req.on("end", () => {
console.log(body);
res.end("Data payload functionally received successfully!");
});
}
});Serving Structural HTML & Static Data Targets
Serving HTML Architecture Context
import fs from 'fs';
const server = http.createServer((req, res) => {
const html = fs.readFileSync('index.html');
res.setHeader("Content-Type", "text/html");
res.end(html);
});Serving Rendered Static Context Targets (CSS / Script Bundles)
if (req.url === "/style.css") {
const css = fs.readFileSync('style.css');
res.setHeader("Content-Type", "text/css");
res.end(css);
}Routing Drawbacks Identification
Attempting manual content type declaration assignments scales incredibly poorly. Each distinct mime type enforces specific repetitive mapping constraints. This explicit difficulty validates exactly why standard implementations integrate Express directly.
Status Headers & Metadata Integrations
HTTP Status Code Assignments
| Code | Assigned Diagnostic Meaning |
|---|---|
| 200 | Success OK Resolution |
| 201 | Created Instance Resolution |
| 400 | Target Rejection Bad Request |
| 404 | Not Directly Found Path |
| 500 | Total Complete Server Error |
// Explicit definition
res.statusCode = 404;
res.end("Not Found");Custom Header Implementation Metadata
res.setHeader("Content-Type", "application/json");
res.setHeader("X-Custom-Header", "NodeServer");- Standard Requirements Use Cases: Assigning Content type mappings consistently.
- Declaring security constraints and explicit JWT Authorization layers.
- Implementing critical CORS validation configurations strictly.
Integrating Streams natively via HTTP
Example Configuration: Extremely Efficient System File Serving
import fs from 'fs';
import http from 'http';
const server = http.createServer((req, res) => {
const stream = fs.createReadStream('scale_file.txt');
stream.pipe(res);
});No Memory Faults
Zero total operational ram constraints observed via buffering.
Velocity Return Limit
Exceptionally fastest immediate chunk return possible natively.
Production Verified
The absolute primary implementation standard adopted broadly.