Building a Simple Web Server
Serve real pages over HTTP with Node's built-in http module
http module already comes with Node.
- create a server with
http.createServerand make itlistenon 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
Every time you open a web page, this two-step dance happens:
- The browser sends a request (for example: GET the page at
/). - The server reads the request and sends back a response (for example: 200 OK, here is some HTML).