createServer
Http & Https create server
1. The Core Architecture: Request-Response Cycle
A web server is a process that listens for incoming network requests and returns a response. In Node.js, this is handled by the Event Loop, allowing the server to handle multiple connections efficiently.
Request (
req): An object containing data about the incoming call (URL, headers, body).Response (
res): An object used to send data back to the client (Status codes, HTML, JSON).
2. Protocol Comparison: HTTP vs. HTTPS
HyperText Transfer Protocol (HTTP)
Port: Default is 80.
Security: Data is sent in "Plain Text." If a hacker intercepts the packet, they can read everything (passwords, credit card info).
Use Case: Local development and internal testing.
HTTP Secure (HTTPS)
Port: Default is 443.
Mechanism: Uses TLS (Transport Layer Security) to encrypt data.
Handshake: Before data is sent, the client and server perform a "handshake" to agree on encryption keys.
3. How HTTPS Encryption Works
HTTPS relies on Public Key Infrastructure (PKI). The server provides a Public Key (Certificate) to the client, while keeping a Private Key secret.
Client Hello: Client requests a secure session.
Server Certificate: Server sends its certificate (public key).
Authentication: Client verifies the certificate with a Certificate Authority (CA).
Key Exchange: A unique symmetric session key is created for that specific session.
4. Implementation Guide
Building the HTTP Server
The http module is built-in. It is used to create a listener on a specific port.
const http = require('http');
const server = http.createServer((req, res) => {
// Setting the HTTP Header
res.writeHead(200, {'Content-Type': 'application/json'});
// Sending the body
res.end(JSON.stringify({ message: "Success" }));
});
server.listen(8080);Transitioning to HTTPS
To move to HTTPS, the server requires two files:
Private Key (
.key): Kept on the server; never shared.Certificate (
.certor.pem): Shared with the browser to prove identity.
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
};
https.createServer(options, (req, res) => {
res.end('Secure Connection Established');
}).listen(443);