Episode 3 of 12

Clients & Servers

Learn how the web works with clients and servers, and create your first HTTP server using Node.js.

Before building web applications, you need to understand how clients and servers communicate over the internet.

How the Web Works

When you type a URL in your browser:

  1. The client (your browser) sends an HTTP request to a server
  2. The server processes the request
  3. The server sends back an HTTP response (HTML, JSON, images, etc.)
  4. The browser renders the response

Node.js excels at building the server side of this equation.

Creating an HTTP Server

Node.js has a built-in http module for creating servers:

const http = require('http');

const server = http.createServer((req, res) => {
    console.log('Request made');
    console.log('URL:', req.url);
    console.log('Method:', req.method);

    // Set response header
    res.setHeader('Content-Type', 'text/html');

    // Send response
    res.write('<h1>Hello from Node.js Server!</h1>');
    res.end();
});

server.listen(3000, 'localhost', () => {
    console.log('Server running at http://localhost:3000');
});

Understanding the Request Object

The req object contains information about the incoming request:

  • req.url — The URL path requested (e.g., /about)
  • req.method — The HTTP method (GET, POST, etc.)
  • req.headers — Request headers

Port and Localhost

Localhost (127.0.0.1) refers to your own computer. The port number (like 3000) is like a door on that computer — different applications listen on different ports. Common ports: 80 (HTTP), 443 (HTTPS), 3000 (development).