Topic 37 of 55
Native HTTP Server Base
Overview
Node.js has a built-in `http` module that allows it to act as a web server without needing external software like Apache or Nginx. While powerful, it is very low-level, which is why frameworks like Express were created on top of it.
Syntax
javascript
const http = require('http');
// Create the server. The callback runs every time a request is received.
const server = http.createServer((req, res) => {
// req: Incoming request details (URL, headers, method)
// res: Object used to formulate and send the response
console.log(`Received ${req.method} request for ${req.url}`);
// 1. Set the response header (Status 200 OK, Content-Type)
res.writeHead(200, { 'Content-Type': 'text/plain' });
// 2. Send the response body and end the connection
res.end('Hello from native Node.js HTTP server!');
});
// Start listening on a port
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});Common Pitfalls
- You MUST call `res.end()` eventually in every branch of your code. If you forget, the client's browser will spin forever waiting for a response and eventually time out.
- The native HTTP server does not parse JSON bodies or query strings automatically. You have to write complex buffer-concatenation code to read POST data.
Real-World Example
Building a basic manual router using just the native HTTP module:
example
javascript
const http = require('http');
const server = http.createServer((req, res) => {
// Manual routing using switch statements
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: "Welcome to the API" }));
} else if (req.url === '/users' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify([{ id: 1, name: "Alice" }]));
} else {
// 404 Not Found fallback
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end("Route not found");
}
});
server.listen(8080);