Skip to content

Building a Simple Web Server

Programming Node.js Difficulty 1/5

Beginning of the lesson

Building a Simple Web Server

Serve real pages over HTTP with Node's built-in http module

Big Idea: A web server is a program that waits for requests and sends back responses. With Node.js you can build one in just a few lines — no extra software to install, because the http module already comes with Node.
By the end you will be able to:
  • create a server with http.createServer and make it listen on a port,
  • read the incoming request (req.url, req.method),
  • send back plain text or HTML with the right Content-Type,
  • always finish a response with res.end().

1. What is a web server? (an analogy)

Think of a restaurant. You (the client, usually a web browser) walk in and ask for something: "I'd like the home page, please." A waiter (the server) takes your order, goes to the kitchen, and brings back a plate. Your order is the request; the plate is the response.

A web server does exactly this, over and over, very fast. It listens for requests coming in on a port (like a numbered door — we will use door number 3000), and for each request it sends back a response: some text, an HTML page, an image, and so on.

Node.js is great for this because it can handle many requests without getting stuck waiting, and the tools to build a server are already built in.

2. The request-response cycle

Client (browser) Server (Node.js) Request -> GET / <- Response 200 OK + HTML
undefined

Every time you open a web page, this two-step dance happens:

  1. The browser sends a request (for example: GET the page at /).
  2. The server reads the request and sends back a response (for example: 200 OK, here is some HTML).

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers