Your first HTTP server
Every website and API you use is a server: a program that waits for requests and sends back responses. Node has a web server built in, the node:http module. Frameworks like Express are built on top of it, so seeing it raw first makes everything later easier to understand.
Request in, response out
When you open http://localhost:3000/hello in a browser, it sends a request like this:
GET /hello HTTP/1.1
Host: localhost:3000
Accept: text/htmland the server replies:
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Hello, world!A request has a method (GET, POST…), a URL path, headers and sometimes a body. A response has a status code (200 OK, 404 Not Found…), headers and a body.
A minimal server
createServertakes a request handler that Node calls for every request, with a request object (req) and a response object (res).listen(3000)starts listening on port 3000. The callback runs once the server is ready.res.end(body)sends the response. Every request must end with a response, or the browser waits until it times out.
On your computer, leave out the
fetchandserver.close()lines, runnode server.js, and openhttp://localhost:3000/helloin your browser. The server keeps running until you press Ctrl+C. In these editors we call our own server withfetchand then close it so the example finishes.
Routing by hand
A real server responds differently depending on the method and the path. That's called routing:
new URL(req.url, base) splits the URL into pathname and searchParams (the query string after ?).
Reading a request body
POST and PUT requests carry data in their body. The request is a readable stream, so the body arrives in chunks that we collect:
Status codes and headers
| Code | Meaning | Use it when |
|---|---|---|
| 200 OK | Success | Returning data |
| 201 Created | A new resource was created | After a successful POST |
| 204 No Content | Success, nothing to return | After a DELETE |
| 400 Bad Request | The client sent something invalid | Malformed JSON, missing fields |
| 401 Unauthorized | Not logged in | Missing or bad credentials |
| 403 Forbidden | Logged in but not allowed | A user editing someone else's data |
| 404 Not Found | No such resource | Unknown URL or id |
| 500 Internal Server Error | The server crashed | A bug or an outage |
Headers describe the response: Content-Type (what the body is), Cache-Control (how long it may be cached), Location (where a new resource lives, or where to redirect), Set-Cookie and many more.
Why use a framework?
Our hand-written server already needs URL matching, JSON parsing, error handling and helper functions, and it would keep growing: cookies, file uploads, authentication, CORS… Express (next lesson) provides all of this, so a route becomes one line:
app.get('/products/:id', (req, res) => res.json(findProduct(req.params.id)));Practice
- Add a
DELETE /messages/:idroute that removes a message and responds with204. - Make the server respond with
405 Method Not AllowedforPUT /messages. - Add a
GET /healthroute that returns{ "status": "ok", "uptime": … }usingprocess.uptime().
1.What must every request handler eventually do?
2.Which status code fits a successful POST that created a new item?
3.Why is the request body read with for await?