From Zero to Senior · The LabالعربيةGitHub

Chapter 4

How the Web Works

4 examples · 3 projects · 5 exercises

In this chapter you will learn

  • what clients and servers are, and how they talk to each other
  • how to read every part of a web address
  • how your computer finds a server anywhere in the world in milliseconds
  • what an HTTP request and response look like, and what status codes mean
  • how a browser turns HTML, CSS and JavaScript into a page, and how to build a tiny web server yourself

Examples

4.2 Reading a web address

JavaScript can take a URL apart for you with new URL(). This is exactly what browsers do with every address you type:

url.js⤓ File
const address = new URL(
  "https://shop.example.com:8080/products/shoes?size=42&color=red#reviews"
);

console.log(address.protocol);
console.log(address.hostname);
console.log(address.port);
console.log(address.pathname);
console.log(address.searchParams.get("size"));
console.log(address.hash);
Recorded output$ node url.js
https:
shop.example.com
8080
/products/shoes
42
#reviews

4.4 The HTTP conversation

Once the browser knows the server’s address, it sends an HTTP request. It is surprisingly readable plain text:

request.txt⤓ File
GET /products/shoes?size=42 HTTP/1.1
Host: shop.example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0) Chrome/131
Accept: text/html
Accept-Language: en-US,en

The server answers with an HTTP response:

response.txt⤓ File
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 5120
Cache-Control: max-age=600

<!doctype html>
<html lang="en">
  <head><title>Shoes</title></head>
  ...

4.7 Project: your own web server

Time to take part in the conversation yourself. Node.js includes everything you need to build a web server in a few lines. The program below plays both roles: it starts a server, and then it acts as a client and asks that server for a page, exactly as a browser would.

server.js⤓ File
Runs with Node.js: node server.js
const http = require("node:http");

// The server: answers every request with a small HTML page.
const server = http.createServer((request, response) => {
  console.log(`Request: ${request.method} ${request.url}`);
  response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
  response.end("<h1>Hello from my server!</h1>");
});

server.listen(3000, async () => {
  console.log("Server ready at http://localhost:3000");

  // The client: ask our own server for a page, like a browser would.
  const reply = await fetch("http://localhost:3000/hello");
  console.log(reply.status, reply.statusText);
  console.log(reply.headers.get("content-type"));
  console.log(await reply.text());

  server.close();
});
Recorded output$ node server.js
Server ready at http://localhost:3000
Request: GET /hello
200 OK
text/html; charset=utf-8
<h1>Hello from my server!</h1>

Practice projects

Project 4.1 · Easy

URL inspector

Take a list of web addresses apart and print the host, path, query and fragment of each one.

You will practise: the parts of a URL and the URL object.

Steps
  1. Before writing code, copy the three addresses from the solution onto paper and underline each part in a different colour, as in Figure 4.1.
  2. Create inspect-urls.js with an array of the three addresses.
  3. For each address, create new URL(text) and print hostname, pathname, search and hash, separated by "|".
  4. Some addresses have no query or fragment, so those properties are empty. Print "-" instead, with url.search || "-".
  5. Compare the output with your paper. Did you find every part correctly?

Hint: for (const text of addresses) repeats the code for each address (Chapter 9), and || picks the right side when the left side is empty (Chapter 8).

Solution
inspect-urls.js⤓ File
const addresses = [
  "https://www.example.com/news/sport?team=ahly&page=2",
  "http://localhost:3000/about",
  "https://shop.example.com/cart#summary",
];

for (const text of addresses) {
  const url = new URL(text);
  console.log(url.hostname, "|", url.pathname, "|", url.search || "-", "|", url.hash || "-");
}
Recorded output$ node inspect-urls.js
www.example.com | /news/sport | ?team=ahly&page=2 | -
localhost | /about | - | -
shop.example.com | /cart | - | #summary

Project 4.2 · Medium

A three-page website with a 404 page

Extend your web server so that it serves a home page, an About page and a Contact page, and answers 404 Not Found for anything else.

You will practise: paths, status codes, and how a server decides what to send.

Steps
  1. Copy server.js from Section 4.7 into site.js.
  2. Above the server, create an object that maps each path to its page: "/", "/about" and "/contact".
  3. Inside the server, look up pages[request.url]. If a page exists, send it with status 200; otherwise send a “Page not found” heading with status 404.
  4. Test four paths, including one that does not exist, and print the path, the status and the page.
  5. Remove server.close(), open http://localhost:3002/about in your browser, and look at the status in the Network tab.

Hint: an object used like this is a small “dictionary” from paths to pages. Real servers do the same thing with many more pages; it is called routing.

Solution
site.js⤓ File
Runs with Node.js: node site.js
const http = require("node:http");

// One small website with three pages, and a 404 page for everything else
const pages = {
  "/": "<h1>Home</h1>",
  "/about": "<h1>About us</h1>",
  "/contact": "<h1>Contact</h1>",
};

const server = http.createServer((request, response) => {
  const page = pages[request.url];
  if (page) {
    response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
    response.end(page);
  } else {
    response.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
    response.end("<h1>Page not found</h1>");
  }
});

server.listen(3002, async () => {
  for (const path of ["/", "/about", "/contact", "/secret"]) {
    const reply = await fetch(`http://localhost:3002${path}`);
    console.log(path, reply.status, await reply.text());
  }
  server.close();
});
Recorded output$ node site.js
/ 200 <h1>Home</h1>
/about 200 <h1>About us</h1>
/contact 200 <h1>Contact</h1>
/secret 404 <h1>Page not found</h1>

Project 4.3 · Challenge

A restaurant menu API

Build a server that answers with data instead of a web page: a restaurant’s menu as JSON, the way real mobile apps get their data.

You will practise: APIs, the Content-Type header, and JSON (Chapter 11 explains it in depth).

Steps
  1. Create menu-api.js with an array of three dishes, each with a name and a price.
  2. For the path /api/menu, answer with status 200, the header Content-Type: application/json, and the body JSON.stringify(menu).
  3. Fetch /api/menu and print the status, the content type and the text you received.
  4. Open the address in your browser with the server running. Most browsers show JSON in a neat, readable way.

Hint: an API (Application Programming Interface) is a server made for programs rather than people. The weather in your phone, the scores in a sports app and the products in a shop app all come from APIs like this one.

Solution
menu-api.js⤓ File
Runs with Node.js: node menu-api.js
const http = require("node:http");

const menu = [
  { name: "Koshari", price: 45 },
  { name: "Falafel plate", price: 60 },
  { name: "Mint tea", price: 25 },
];

const server = http.createServer((request, response) => {
  if (request.url === "/api/menu") {
    response.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
    response.end(JSON.stringify(menu));
  } else {
    response.writeHead(404);
    response.end();
  }
});

server.listen(3003, async () => {
  const reply = await fetch("http://localhost:3003/api/menu");
  console.log(reply.status, reply.headers.get("content-type"));
  console.log(await reply.text());
  server.close();
});
Recorded output$ node menu-api.js
200 application/json; charset=utf-8
[{"name":"Koshari","price":45},{"name":"Falafel plate","price":60},{"name":"Mint tea","price":25}]

Exercises

Exercise 4.1 · Easy

Write down the protocol, host, path and query of https://www.example.com/search?q=javascript&page=2. Check your answer by changing url.js.
The book's short answer
Protocol https:, host www.example.com, path /search, query ?q=javascript&page=2.
Show the solution
my-url.js⤓ File
// url.js from the chapter, with the address from the exercise.
const address = new URL("https://www.example.com/search?q=javascript&page=2");

console.log("Protocol:", address.protocol);
console.log("Host:", address.hostname);
console.log("Path:", address.pathname);
console.log("Query:", address.search);

// Each part of the query on its own:
console.log("q =", address.searchParams.get("q"));
console.log("page =", address.searchParams.get("page"));
Recorded output$ node my-url.js
Protocol: https:
Host: www.example.com
Path: /search
Query: ?q=javascript&page=2
q = javascript
page = 2

Exercise 4.2 · Easy

Visit a page that does not exist on any website, such as /this-page-does-not-exist. Open the Network tab and find the status code.
The book's short answer
The status code is 404.
Show the solution
not-found.js⤓ File
Runs with Node.js: node not-found.js
// A page that does not exist: the server answers with status code 404.
// In the browser you would see this number in the Network tab, in the Status column.
const http = require("node:http");

const server = http.createServer((request, response) => {
  if (request.url === "/") {
    response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
    response.end("<h1>Home</h1>");
  } else {
    response.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
    response.end("<h1>Page not found</h1>");
  }
});

server.listen(3011, async () => {
  for (const path of ["/", "/this-page-does-not-exist"]) {
    const reply = await fetch(`http://localhost:3011${path}`);
    console.log(path, "->", reply.status, reply.statusText);
  }
  server.close();
});
Recorded output$ node not-found.js
/ -> 200 OK
/this-page-does-not-exist -> 404 Not Found

Exercise 4.3 · Medium

Change server.js so the page shows your name in the heading and a paragraph about you, using <p> after the <h1>.
The book's short answer
Change the body to "<h1>Your name</h1><p>About you</p>".
Show the solution
about-me.js⤓ File
Runs with Node.js: node about-me.js
// server.js with a heading and a paragraph about me.
const http = require("node:http");

const server = http.createServer((request, response) => {
  response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
  response.end("<h1>Sara Ahmed</h1><p>I am learning to code with Bit, and this page comes from my own server.</p>");
});

server.listen(3012, async () => {
  console.log("Open http://localhost:3012 in your browser (this demo fetches it itself):");
  const reply = await fetch("http://localhost:3012/");
  console.log(await reply.text());
  server.close();
});
Recorded output$ node about-me.js
Open http://localhost:3012 in your browser (this demo fetches it itself):
<h1>Sara Ahmed</h1><p>I am learning to code with Bit, and this page comes from my own server.</p>

Exercise 4.4 · Medium

In server.js, change the status code from 200 to 404. What does the output show now? Does the browser still display the page?
The book's short answer
The output shows 404 Not Found. The browser still shows the page you sent: a status code describes the result; it does not stop the body.
Show the solution
status-404.js⤓ File
Runs with Node.js: node status-404.js
// server.js with 404 instead of 200.
const http = require("node:http");

const server = http.createServer((request, response) => {
  response.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
  response.end("<h1>Hello from my server!</h1>");
});

server.listen(3013, async () => {
  const reply = await fetch("http://localhost:3013/hello");
  console.log(reply.status, reply.statusText);
  // The body still arrives: the status code describes the result, it does not stop the page.
  console.log(await reply.text());
  server.close();
});
Recorded output$ node status-404.js
404 Not Found
<h1>Hello from my server!</h1>

Exercise 4.5 · Challenge

Make the server answer differently depending on the path: if request.url is "/about", send an “About me” page; otherwise send the normal page. (Hint: use an if, from Chapter 8.)
The book's short answer
if (request.url === "/about") {
  response.end("<h1>About me</h1>");
} else {
  response.end("<h1>Hello from my server!</h1>");
}
Show the solution
routes.js⤓ File
Runs with Node.js: node routes.js
// A different page for /about, and the normal page for every other path.
const http = require("node:http");

const server = http.createServer((request, response) => {
  response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
  if (request.url === "/about") {
    response.end("<h1>About me</h1>");
  } else {
    response.end("<h1>Hello from my server!</h1>");
  }
});

server.listen(3014, async () => {
  for (const path of ["/", "/about", "/anything-else"]) {
    const reply = await fetch(`http://localhost:3014${path}`);
    console.log(path, "->", await reply.text());
  }
  server.close();
});
Recorded output$ node routes.js
/ -> <h1>Hello from my server!</h1>
/about -> <h1>About me</h1>
/anything-else -> <h1>Hello from my server!</h1>