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:3000

This 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: 200

http.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.

๐Ÿ“ Quick Quiz

1. Which method creates an HTTP server?

2. What ends and sends the HTTP response?

3. What are the two parameters of the server callback?