A first HTTP server with Node.js
Trace a request from a page to a Node server and back.
- Explain request, route, status and response body
- Build a small server with node:http
- Keep request handling separate from browser rendering
When a page calls fetch("/api/hello"), the browser sends an HTTP request. A server receives it, decides what route was requested, and sends a status, headers and body. Node.js provides createServer in node:http. The browser then reads the response and updates its DOM. This is how a product catalog, dashboard or sign-up flow connects frontend and backend JavaScript.
Try it
Up to 15 XPFollow one request
Predict the steps between a browser click and the text it shows.
1import { createServer } from "node:http";
2
3const server = createServer((request, response) => {
4 response.setHeader("Content-Type", "application/json; charset=utf-8");
5 if (request.method === "GET" && request.url === "/api/hello") {
6 response.statusCode = 200;
7 response.end(JSON.stringify({ message: "Hello from Node" }));
8 } else {
9 response.statusCode = 404;
10 response.end(JSON.stringify({ error: "Not found" }));
11 }
12});
13server.listen(3000, "127.0.0.1", () => console.log("Listening on http://127.0.0.1:3000"));Save the file, run it with node server.mjs, then visit http://127.0.0.1:3000/api/hello and /missing. Stop it with Ctrl+C. The server is deliberately small: real services also validate input, set limits, handle failures and protect private resources. See the Node.js introduction.
1const response = await fetch("/api/hello");
2if (!response.ok) throw new Error("HTTP " + response.status);
3const data = await response.json();
4document.querySelector("#greeting").textContent = data.message;Key takeaways
A browser sends a request; a server chooses a route and sends a response.
HTTP status and Content-Type tell the client how to interpret the body.
The browser renders results; Node.js handles server work and private resources.
Lesson quiz
2 questions · pass with 2 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write JavaScript
Write the program, run it against the test cases, and use the feedback to build your JavaScript skills.
Route two requests
Input is a path such as /api/hello. Write a pure handle(path) function that returns an object with status and body. For /api/hello, return 200 and Hello from Node; otherwise return 404 and Not found. Print status body. This models the route decision without starting a server in the browser exercise.
- Known route
- Unknown route
JavaScript runs in a sandboxed browser frame with a 1.5 second time limit. Input is available as the string variable input.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…