16 min read
Create a Node.js HTTP server without Express
In one sentence: An HTTP server is a program that waits for requests and calls a function of yours with each one. With Node.js's node:http module, the start line, the headers and the body you saw in Phase 2 arrive in variables, and you write the response: code, headers and body.
What you will learn
- Start a server with createServer and listen, and explain what req and res are.
- Read a request's method, path and headers, and its body, which arrives in chunks.
- Decide what to answer on each route with if, and return 200, 201, 400, 404, 405 (with its Allow header) or 422.
- Restart the server when you save with node --watch, and check each response with curl.
Before you start, read: 03-typescript.md phase-2/01-request-and-response.md
The problem
Section titled “The problem”The shop’s nginx, in Phase 2, had an address, /api/orders, that gave the same answer to everything: a 200 and {"orders":[]}. Imagine Luis sends an order for three mugs there. He gets a 200 and thinks it went well, but the order isn’t anywhere: nginx didn’t even read it.
And it can’t. An nginx configuration says “at this address, answer this.” Taking an order means reading the Body (of a request or response)The data an HTTP message carries after the blank line that ends the headers, such as the fields of a form, some JSON or an image. The Content-Type header says what format it’s in, and Content-Length how many bytes it takes up.Go to definition, checking that the product exists, saving it and answering 201 with its number: it takes a program that decides on every RequestThe message a client sends to a server to ask for something, for example “give me the home page.”Go to definition.
In lesson 1 of Phase 2 you did that work by hand with nc. Now you write the program that does it for you, with only what comes with Node.jsA program that runs JavaScript outside the browser, on your computer or on a server. It uses the same engine as Chrome and adds what a web page can’t do, like reading files or listening on a port.Go to definition, no FrameworkReady-made code that solves what almost every program of one kind repeats, such as a server (reading each request, deciding which route handles it and responding), and that calls your functions when the time comes. You write only what’s specific to your application. Hono, Express and Fastify are frameworks for servers.Go to definition (the ready-made code almost every server uses). And you’ll see there’s no magic: they’re the same lines of text, now in VariableA name that holds a value to use later, such as price = 8.5. In JavaScript it’s created with const, if it won’t be swapped for another value, or with let, if it will.Go to definition.
The analogy
Section titled “The analogy”The analogy
Think of a company’s mail. In the mail room they open each envelope and leave the letter on your desk with a slip: what it asks for (the method), which department it’s for (the path) and who sends it (the headers). Next to it, a blank reply form.
You read, decide and fill in the form: a code (“done,” “that doesn’t exist,” “we don’t do that here”) and the content. The mail room sends it. Node.js is the mail room, and your code is the person at the desk: you write every response.
Where the analogy breaks down
- The content doesn’t come inside the envelope: it arrives in chunks, and you have to put them together before reading it.
- The mail room doesn’t check the letter. If someone asks for −5 mugs, it passes it on all the same.
- If you forget to send the reply, nobody warns you: whoever wrote is left waiting.
How it really works
Section titled “How it really works”The files in this lesson
Section titled “The files in this lesson”You’re still in the project from lesson 3, in ~/backend-course/phase-3/shop-api. When you finish this lesson, it will have these files:
Directorysrc/
- data.ts the products and the orders (before, products.ts)
- app.ts the server: the routes and the responses
- server.ts makes it listen on port 3000
Directorytest/
- server.test.ts the tests
- package.json
Write each file as you read it. src/data.ts is your src/products.ts with another name (mv src/products.ts src/data.ts), without the total function and with the orders you’ll see below. src/main.ts isn’t needed anymore: delete it.
You don’t write the tests: they come in this lesson’s folder. Download it next to your project and copy its test/ folder into yours; if you get stuck, compare your code with the download’s:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/04-http-server.tar.gztar -xzf 04-http-server.tar.gzcp -r 04-http-server/test shop-api/cp -r copies a whole folder (lesson 2 of Phase 1).
A server is a function Node calls with every request
Section titled “A server is a function Node calls with every request”// Starts the server: it listens on port 3000, only on this computer.import { createShopServer } from './app.ts';
const server = createShopServer();server.listen(3000, '127.0.0.1', () => { console.log('The shop is listening on http://localhost:3000');});import { createShopServer } from './app.ts'brings fromapp.tsthe FunctionA named piece of code that takes some data, does something with it and returns a result. It’s written once and used as many times as needed.Go to definition that creates the server.server.listen(3000, '127.0.0.1', …)makes it listen on PortA number, from 0 to 65535, that says which program on a computer a connection is for. The computer has an address; each listening program has its port.Go to definition 3000 of the address127.0.0.1, the one for localhostA name that always means “this same computer.” When you open localhost:8080, both the client and the server are on your machine.Go to definition: only your computer can call it. A public server listens on all the machine’s addresses,0.0.0.0; you’ll do that in Phase 8.- The function at the end is called by Node once it’s listening. The program doesn’t end: it waits for requests until you stop it with Ctrl + C, like any ProcessA running program. When you start a server, the operating system creates a process that stays alive waiting for requests.Go to definition from Phase 1.
app.ts starts like this:
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';import { createOrder, findOrder, findProduct, orders, products } from './data.ts';node:http is a ModuleA code file that offers some of its pieces to other files, which bring them in with import. This way a program is split across several files and can use the pieces that come with Node.js or with a package.Go to definition that comes with Node (that’s what the node: prefix says): there’s nothing to install with npmThe package manager of Node.js, which comes installed with it. It’s both a command, which downloads packages into your project, and a public catalog on the internet where anyone can publish them. Although it’s often read as “Node Package Manager,” officially it isn’t an acronym.Go to definition. From it come createServer and the TypeThe kind of data that can go in a place, such as a number, a piece of text or a product with its name and its price. In TypeScript it’s written after a colon (price: number), and it helps find errors before running the program.Go to definition of the request and the response. The second line brings what’s in data.ts. At the end of the file is the function server.ts uses:
export function createShopServer() { return createServer((req, res) => { handle(req, res).catch(() => sendJson(res, 500, { error: 'Internal server error' })); });}createServer(…)creates the server and gives it the function that will handle each request. Node calls it once per request with two ObjectA value that groups several pieces of data, each with its own name, such as { name: "Mug", price: 8.5 }. Each piece is read with a period and its name, such as product.price.Go to definition:req(request), the request that has arrived, andres(response), the response you’re going to write.handle(req, res)decides what to answer. You’ll see it in a moment..catch(…): ifhandlefails for some unexpected reason, the client gets a500instead of being left waiting. Errors are lesson 8.exportletsserver.tsand the tests usecreateShopServer.
The Phase 2 request, in variables
Section titled “The Phase 2 request, in variables”Node reads the bytes that arrive over the connection, separates the start line and the headers, and gives you everything in req:
| In the message | In the code | For example |
|---|---|---|
| The HTTP methodHTTP stands for HyperText Transfer Protocol.The word every HTTP request starts with, which says what the client wants to do with what it asks for. GET is reading, POST sending data, PUT replacing, PATCH changing a part and DELETE deleting.Go to definition, in the start line | req.method |
'POST' |
| The path and the Query stringThe part of a URL that comes after “?”: data in name=value pairs separated by “&”, such as q=mug&sort=price. It travels to the server attached to the path, and it’s used to search, filter or choose a page of results.Go to definition, in the start line | req.url |
'/products?sort=price' |
| The HeaderInformation a protocol puts in front of its data to do its job. In HTTP they are text lines of the form “Name: value”, such as Host or Content-Type; in TCP or IP they are numbers in fixed positions, such as ports or addresses.Go to definition | req.headers |
{ host: 'localhost:3000', 'content-type': 'application/json', … } |
| The body, after the empty line | req itself, which is read in chunks |
{"productId":2,"quantity":3} |
Notice two things:
req.urlisn’t a whole URL: it’s what travels in the start line, the path with its query string. The server’s name goes in theHostheader.- Header names arrive in lowercase. HTTP doesn’t care about upper or lower case (lesson 4 of Phase 2), so Node makes them all the same: you always look up
req.headers['content-type'].
node:http only takes the request apart. What to answer is up to you.
Responding: code, headers and body
Section titled “Responding: code, headers and body”All the shop’s JSON responses go through this function:
function sendJson(res: ServerResponse, status: number, data: unknown, headers = {}) { res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', ...headers }); res.end(JSON.stringify(data));}
function methodNotAllowed(res: ServerResponse, allowed: string) { sendJson(res, 405, { error: 'Method not allowed' }, { Allow: allowed });}sendJsonis ours, not Node’s. It takesres, the Status codeA three-digit number at the start of every HTTP response that sums up what happened. 200 means “all good,” 404 “that doesn’t exist” and 400 “your request is malformed.”Go to definition, the data and, if needed, more headers (= {}: if it isn’t given any, none).res.writeHead(status, {…})writes the status line and the headers: theHTTP/1.1 201 Createdand theContent-Type. Node adds the phrase,Created, based on the number....headerscopies the extra headers into the same object. That’s howLocationorAlloware added.JSON.stringify(data)turns the data into JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition text, andres.end(…)writes it as the body and marks the response as finished. Withoutres.end, the client waits forever.methodNotAllowedanswers405withAllow, the methods that are accepted, as the standard requires (lesson 2 of Phase 2).
Choosing what to do: routes, with if
Section titled “Choosing what to do: routes, with if”handle looks at the Route (on a server)Each combination of HTTP method and URL path that a server knows how to handle, such as GET /products, together with the function that responds to those requests. A request that matches no route gets a 404.Go to definition and the method, and gives the right answer. Its beginning:
async function handle(req: IncomingMessage, res: ServerResponse) { const { pathname } = new URL(req.url ?? '/', 'http://localhost');
if (pathname === '/') { res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end("Ana and Luis's shop. Try /products and /orders.\n"); return; }
if (pathname === '/products') { if (req.method !== 'GET') return methodNotAllowed(res, 'GET'); return sendJson(res, 200, products); }asynclets the function wait withawait(lesson 2).new URL(req.url ?? '/', 'http://localhost')builds a whole URL to separate its parts;'http://localhost'is only a base, becausereq.urldoesn’t include the server.??means “if it’s missing, use'/'.”const { pathname } = …takes thepathnamepart out of that URL and stores it in a variable with the same name. It’s the path without the query string:/products?sort=pricealso goes into/products.if (pathname === '/'):===compares, and if they’re equal the block runs.returnends the function. Without it, the code would keep going down and try to answer again.- On
/products, the method comes first: if it isn’tGET,405withAllow: GET; if it is, the list with a200.
Next, a specific product, like /products/2:
const route = pathname.match(/^\/products\/(\d+)$/);if (route) { if (req.method !== 'GET') return methodNotAllowed(res, 'GET'); const product = findProduct(Number(route[1])); if (!product) return sendJson(res, 404, { error: 'No such product' }); return sendJson(res, 200, product);}pathname.match(/^\/products\/(\d+)$/)compares the path with a pattern, a regular expression: “starts with/products/, goes on with one or more digits (\d+) and ends.” The parentheses keep the digits:route[1]is the text'2', andNumber(…)turns it into the number 2. If it doesn’t fit,matchreturnsnulland theifisn’t entered.if (!product):!means “not.” IffindProducthasn’t found anything,404.
And the end, with the orders:
if (pathname === '/orders') { if (req.method === 'GET') return sendJson(res, 200, orders); if (req.method !== 'POST') return methodNotAllowed(res, 'GET, POST'); return newOrder(req, res); }
const orderRoute = pathname.match(/^\/orders\/(\d+)$/); if (orderRoute) { if (req.method !== 'GET') return methodNotAllowed(res, 'GET'); const order = findOrder(Number(orderRoute[1])); if (!order) return sendJson(res, 404, { error: 'No such order' }); return sendJson(res, 200, order); }
sendJson(res, 404, { error: 'No such route' });}/ordersacceptsGET, the list, andPOST, which creates an order withnewOrder(you’ll see it in a moment). With any other method,405andAllow: GET, POST./orders/1works like/products/2, with its own pattern andfindOrder. It’s the address each new order gets; if it doesn’t exist,404.- The last line is only reached if no
ifhas answered:404.
404 is a route that doesn’t exist; 405, a route that exists with a method it doesn’t accept. It works, but every new route is another if. A framework saves you that part: you’ll see it in lesson 5.
The body arrives in chunks
Section titled “The body arrives in chunks”The method and the headers are in req from the start; the body isn’t. It can take up megabytes, like a photo, and it travels in several TCP SegmentOne of the pieces TCP cuts the data into before sending it. It carries a header with the ports, the sequence number and the acknowledgment number (ACK), plus a chunk of the data. It travels inside an IP packet.Go to definition (Phase 0). Instead of waiting until it has the whole thing, Node gives you each chunk as it arrives: it’s a StreamData that arrives or is sent little by little, in chunks, instead of all at once, so a program can read it as it arrives. In a Node.js server, the body of a request is a stream.Go to definition.
// The body arrives in chunks (it's a stream): they're all put together before reading it.async function readBody(req: IncomingMessage): Promise<string> { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(chunk); return Buffer.concat(chunks).toString('utf8');}const chunks: Buffer[] = []creates an empty ArrayA list of values in order, such as [20, 8.5, 35]. Each value is read by its position, which starts counting at 0: prices[0] is the first one.Go to definition, a list to keep the chunks in. Each chunk is aBuffer: bytes, not text yet.for await (const chunk of req)goes through the chunks as they arrive, andpushadds each one to the list.awaitwaits for the next one without stopping the rest of the server (why, in lesson 9).- When there are no chunks left,
Buffer.concatputs them together andtoString('utf8')turns the bytes into text. Promise<string>says what it returns: a PromiseA value that isn’t there yet but will arrive, like the text of a file that is being read. Until it arrives, the program can go on with other things; with await, it waits for it.Go to definition of a text, which arrives when the body is complete.
They’re put together before converting them because an é takes up two bytes (Phase 2) and can end up split between two chunks.
A new order: JSON in, JSON out
Section titled “A new order: JSON in, JSON out”async function newOrder(req: IncomingMessage, res: ServerResponse) { let data: { productId: number; quantity: number }; try { // "as" promises TypeScript a shape that nobody has checked: lesson 7 fixes that. data = JSON.parse(await readBody(req)) as { productId: number; quantity: number }; } catch { return sendJson(res, 400, { error: 'The body is not valid JSON' }); } // The JSON was read, but it asks for something that doesn't exist: 422 (Phase 2, lesson 3). if (!findProduct(data.productId)) { return sendJson(res, 422, { error: 'No such product' }); } const order = createOrder(data.productId, data.quantity); sendJson(res, 201, order, { Location: `/orders/${order.id}` });}let data: { … }creates the variable before thetry, with the expected shape, so it can be used afterwards. It’sletbecause it gets its value later.JSON.parse(await readBody(req))waits for the whole body and turns the JSON text into data. If it isn’t valid JSON, it throws an error (an ExceptionAn error a program throws when it can’t go on with what it was doing, like reading a JSON that arrives cut off. It travels up through the code until some part catches it; if none does, the program ends.Go to definition).try { … } catch { … }means “try this; if it fails, do this instead”: here, a400, because the server couldn’t even read the data.- If the product doesn’t exist,
422: the JSON was read, but it asks for something that doesn’t exist. It’s the rule from lesson 3 of Phase 2:400if the request can’t be read, and422if it can be read and the data isn’t valid. - If everything goes well,
createOrdersaves it and the response is a201 CreatedwithLocation, the address of the new order.`/orders/${order.id}`is a text with a gap (lesson 2): with order 1,/orders/1.
The as lies to TypeScriptA language that is JavaScript with types: annotations that say what kind of data goes in each place, such as a number or a piece of text. The editor and the TypeScript checker warn about errors before the program runs, and Node.js runs it by erasing the types.Go to definition. It tells it “trust me: the data has this shape,” and nobody checks it: JSON.parse returns whatever arrived, and the types are erased when it runs (lesson 3). If "quantity": -5 arrives, it goes through. Lesson 7 fixes it.
The orders are kept in data.ts:
export const orders: Order[] = [];
export function findProduct(id: number): Product | undefined { return products.find((product) => product.id === id);}
export function findOrder(id: number): Order | undefined { return orders.find((order) => order.id === id);}
export function createOrder(productId: number, quantity: number): Order { const order: Order = { id: orders.length + 1, productId, quantity, status: 'pending' }; orders.push(order); return order;}ordersis a list in memory: when the server stops, it’s lost. The database arrives in Phase 5.findProductyou already had, andfindOrderdoes the same with the orders: it returns the one with thatid, orundefinedif there isn’t one.createOrdergives it the next number (orders.length + 1), marks it'pending'and adds it withpush.
node --watch: the server restarts when you save
Section titled “node --watch: the server restarts when you save”Your package.json still starts main.ts. Change start and add dev with npm pkg set, as in lesson 1, from shop-api:
npm pkg set scripts.start="node src/server.ts" scripts.dev="node --watch src/server.ts"It doesn’t print anything if it goes well. It ends up like this, with dev at the end of scripts (the order doesn’t matter):
{ "name": "shop-api", "version": "1.0.0", "private": true, "type": "module", "engines": { "node": ">=24" }, "scripts": { "start": "node src/server.ts", "dev": "node --watch src/server.ts", "test": "node --test", "check": "tsc --noEmit" }, "devDependencies": { "@types/node": "26.6.4", "typescript": "7.0.2" }}npm startrunsnode src/server.ts. Node reads your code when it starts: if you change a file, the running server doesn’t notice.npm run devadds--watch: Node watchesserver.tsand the files it imports, and restarts the server every time you save one. It’s for when you’re programming.npm testruns the tests, andnpm run checkchecks the types (lesson 3).
The tests you copied start the server on a free port and make the same requests you’ll make with curl, checking codes, headers and bodies. You’ll learn to write them in Phase 10.
Try it
Section titled “Try it”The goal: get the shop’s API running, place an order and find the order it accepts and shouldn’t. The outputs are from Node 26.11.1 and curl 8.14.1, on Linux; on a Mac they come out the same, with other dates.
1. Start the server
cd ~/backend-course/phase-3/shop-apinpm startWhat you will see:
> shop-api@1.0.0 start> node src/server.ts
The shop is listening on http://localhost:3000npm first writes which script it runs. The terminal stays busy: the server is waiting. Open another terminal for the next steps. If you get EADDRINUSE, there’s already another server on port 3000, maybe yours in another terminal: stop it with Ctrl + C. If you get Cannot find module with src/main.ts, you’re missing the npm pkg set from above.
2. Ask for the product list
curl -i localhost:3000/productsWhat you will see:
HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8Date: Tue, 13 Oct 2026 11:18:27 GMTConnection: keep-aliveKeep-Alive: timeout=5Transfer-Encoding: chunked
[{"id":1,"name":"T-shirt","price":20},{"id":2,"name":"Mug","price":8.5},{"id":3,"name":"Hoodie","price":35}]sendJson writes the 200 and the Content-Type; Node, the rest of the headers. The JSON doesn’t end in a line break, so the prompt comes out stuck to it (zsh puts a %). If you get Couldn't connect to server, the server isn’t running: go back to step 1.
3. A product that exists
curl localhost:3000/products/2What you will see:
{"id":2,"name":"Mug","price":8.5}The path fit the pattern, and route[1] was '2'. Without -i, curl only writes the body.
4. A product that doesn't exist
curl -i localhost:3000/products/99What you will see:
HTTP/1.1 404 Not FoundContent-Type: application/json; charset=utf-8Date: Tue, 13 Oct 2026 11:18:27 GMTConnection: keep-aliveKeep-Alive: timeout=5Transfer-Encoding: chunked
{"error":"No such product"}The pattern fits, but findProduct(99) doesn’t find anything: 404, with the message in JSON so a program can read it. With curl -i localhost:3000/offers you get another 404: No such route.
5. Place an order and look it up
curl -i --json '{"productId":2,"quantity":3}' localhost:3000/orderscurl localhost:3000/orders/1What you will see:
HTTP/1.1 201 CreatedContent-Type: application/json; charset=utf-8Location: /orders/1Date: Tue, 13 Oct 2026 11:18:27 GMTConnection: keep-aliveKeep-Alive: timeout=5Transfer-Encoding: chunked
{"id":1,"productId":2,"quantity":3,"status":"pending"}{"id":1,"productId":2,"quantity":3,"status":"pending"}--json sends a POST with that body and Content-Type: application/json (Phase 2). A 201 arrives with Location: /orders/1, and the second command asks for that address: the same order, already saved. The two responses come out stuck together. curl localhost:3000/orders shows the whole list, which empties if you stop the server: it’s in memory.
6. A body that isn't JSON
curl -i --json 'I want two mugs' localhost:3000/ordersWhat you will see:
HTTP/1.1 400 Bad RequestContent-Type: application/json; charset=utf-8Date: Tue, 13 Oct 2026 11:18:27 GMTConnection: keep-aliveKeep-Alive: timeout=5Transfer-Encoding: chunked
{"error":"The body is not valid JSON"}JSON.parse has failed, the catch has caught it and the response is a 400: the server couldn’t read the data. And it’s still running.
7. An order for a product that doesn't exist
curl -i --json '{"productId":99,"quantity":1}' localhost:3000/ordersWhat you will see:
HTTP/1.1 422 Unprocessable EntityContent-Type: application/json; charset=utf-8Date: Tue, 13 Oct 2026 11:18:27 GMTConnection: keep-aliveKeep-Alive: timeout=5Transfer-Encoding: chunked
{"error":"No such product"}The JSON is read fine, but product 99 doesn’t exist: 422. In step 4 the address didn’t exist (404); here /orders exists, and what isn’t valid is the data. Node writes the old phrase, Unprocessable Entity (today, Unprocessable Content), but programs only look at the number.
8. A method the route doesn't accept
curl -i -X DELETE localhost:3000/productsWhat you will see:
HTTP/1.1 405 Method Not AllowedContent-Type: application/json; charset=utf-8Allow: GETDate: Tue, 13 Oct 2026 11:18:27 GMTConnection: keep-aliveKeep-Alive: timeout=5Transfer-Encoding: chunked
{"error":"Method not allowed"}/products exists, but only for reading: 405 and Allow: GET, the rule backenddesdecero.com didn’t follow in lesson 2 of Phase 2.
Challenge: send curl -i --json '{"productId":2,"quantity":-5}' localhost:3000/orders. What does the shop answer? Why doesn’t it reject it?Show answer
It accepts it:
HTTP/1.1 201 CreatedContent-Type: application/json; charset=utf-8Location: /orders/2Date: Tue, 13 Oct 2026 11:18:27 GMTConnection: keep-aliveKeep-Alive: timeout=5Transfer-Encoding: chunked
{"id":2,"productId":2,"quantity":-5,"status":"pending"}The code only checks that the body is JSON and that the product exists. The as promises that quantity is a number, and -5 is one, even though it makes no sense. In lesson 7, this will be a 422.
See what arrives
Section titled “See what arrives”Stop the server with Ctrl + C and start it in development mode:
9. Start with --watch
npm run devWhat you will see:
> shop-api@1.0.0 dev> node --watch src/server.ts
The shop is listening on http://localhost:3000Open src/app.ts in your editor and add this line at the beginning of handle, right before const { pathname }:
console.log(req.method, req.url, req.headers);console.log writes whatever you give it to the terminal. Save, repeat step 2 in the other terminal and look at the server’s:
Change detected in '/Users/ana/backend-course/phase-3/shop-api/src/app.ts'Restarting 'src/server.ts'The shop is listening on http://localhost:3000GET /products { host: 'localhost:3000', 'user-agent': 'curl/8.14.1', accept: '*/*' }Node has seen the change, cleared the terminal and restarted the server on its own. After that, your line: curl’s method, path and headers, in lowercase. (We’ve replaced the Linux path with a Mac one; your version of curl will be different.) If Restarting doesn’t show up, check that you saved and that you started with npm run dev. When you’re done, delete the line.
10. Run the tests
npm testWhat you will see:
> shop-api@1.0.0 test> node --test
✔ GET / answers with text (17.080799ms)✔ GET /products returns all three in JSON (2.493188ms)✔ GET /products/2 returns the mug; /products/99, a 404 (7.589451ms)✔ POST /orders creates an order: 201 with Location (13.138482ms)✔ the Location address exists; an order that does not exist, 404 (6.7115ms)✔ POST /orders with a body that is not JSON: 400 (9.882267ms)✔ POST /orders with a product that does not exist: 422 (1.654833ms)✔ a method the route does not accept: 405 with Allow (1.580597ms)✔ a route that does not exist: 404 (1.041919ms)ℹ tests 9ℹ suites 0ℹ pass 9ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 220.37977Nine tests, one for each thing the lesson promises, and fail 0. They use another port, so they don’t bother the running server; your times will be different. If one fails, it comes out with ✖ and what it expected next to what it got: compare your code with the lesson’s. If you get tests 0, you haven’t copied the test/ folder from the download.
You have already seen it
Section titled “You have already seen it”- In Phase 2, with
nc. What you typed by hand, the status line, the headers and the body, is now written byres.writeHeadandres.end. - In the shop’s nginx. Each
locationwith itsreturnwas a route with a fixed response. Yourifs also read the body and decide. - In the browser. Open
http://localhost:3000/products: the browser makes aGETand shows you the JSON. In DevTools’ Network tab (how to open them) you’ll see the same headers as withcurl -i.
Common mistakes
Section titled “Common mistakes”- Forgetting the
returnafter answering. The code reaches another response: the client gets the first one, but Node throwsError [ERR_HTTP_HEADERS_SENT]: Cannot write headers after they are sent to the clientand the server crashes. - Forgetting
res.end. The response never ends, andcurlis left waiting. - Comparing
req.urlwith the route./products?sort=priceisn’t/products, and you answer404. Compare thepathname. - Starting it twice. The second one fails with
Error: listen EADDRINUSE: address already in use 127.0.0.1:3000: the port already belongs to the first.
Summary
Section titled “Summary”createServertakes a function that Node calls with every request:reqis what arrives andres, the response you write.listenmakes it listen on a port.- The request is in variables:
req.method,req.url(path and query string) andreq.headers(in lowercase). The body is a stream: it arrives in chunks. - Routes are
ifs on thepathnameand the method:404if the route doesn’t exist;405withAllowif it doesn’t accept the method. - If the body isn’t JSON,
try/catchand a400; if it is, but it asks for a product that doesn’t exist,422. Theaschecks nothing: lesson 7 will. npm run dev(node --watch) restarts the server when you save, andnpm testchecks that it answers what it promises.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Anatomy of an HTTP Transaction (Node.js): a request in
node:http, fromcreateServertores.end, with the body as a stream. - HTTP (Node.js documentation): everything
reqandreshave. - Regular expressions (MDN): how patterns like the one for
/products/2are written. - JSON.parse() (MDN): what it returns and when it throws an error.