JavaScript: an HTTP server and client on the loopback interface

HTTP is a text-based request/response protocol on top of TCP. A request has a method, a path, headers, and an optional body. A response has a status code, headers, and a body. Status codes group by meaning: 2xx success, 3xx redirects, 4xx client errors such as 404 Not Found, and 5xx server errors.

JavaScript
const http = require("node:http");

const server = http.createServer((req, res) => {
  const known = req.url === "/hello";
  res.statusCode = known ? 200 : 404;
  res.setHeader("Content-Type", "text/plain");
  res.end(known ? "Hello" : "Not found");
});

server.listen(0, "127.0.0.1", async () => {
  const base = "http://127.0.0.1:" + server.address().port;
  for (const path of ["/hello", "/missing"]) {
    const response = await fetch(base + path);
    console.log(path + " -> " + response.status + " " + (await response.text()));
  }
  server.close();
  server.closeAllConnections();
});
Read the full lesson