Node.js ยท Chapter 12 of 43
The http Module
Node's built-in `http` module lets you create web servers and make HTTP requests without any external libraries.
While frameworks like Express make things easier, understanding the raw `http` module helps you see what's happening underneath.
Creating a server
`http.createServer()` takes a callback that runs for every incoming request, receiving `req` (request) and `res` (response) objects.
Sending a response
Use `res.writeHead()` to set status and headers, then `res.end()` to send the body and finish the response.
Example 1 (javascript)
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!');
});
server.listen(3000);Output
Server running on http://localhost:3000This creates a minimal server responding to every request with plain text.
Example 2 (javascript)
http.get('http://example.com', res => {
console.log('Status:', res.statusCode);
});Output
Status: 200http.get() makes an outgoing HTTP GET request from Node.js.
Key points
- http.createServer() builds a web server.
- The callback receives req and res objects.
- res.end() finishes and sends the response.
- http.get() lets Node.js act as an HTTP client too.
๐ก Note: In real projects, frameworks like Express wrap the http module for convenience.
