Express basics · core
The http module under Express
Express is a thin layer over Node's http module: http.createServer gives you a request (a readable stream) and a response (a writable stream) for every request, and Express adds routing, middleware and helpers like res.json.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- http.createServer((req, res) => ...) calls your function for every request. req has method, url, headers and the body as a stream; res has statusCode, setHeader, write and end.
- Without a framework you parse the URL yourself (new URL(req.url, 'http://localhost')), collect body chunks, JSON.parse them, and set Content-Type.
- Every request must end with res.end() (Express's res.send/res.json call it). Otherwise the client waits until a timeout.
- You cannot set status or headers after the body has started: that is the 'Cannot set headers after they are sent to the client' (ERR_HTTP_HEADERS_SENT) error.
- app.listen() creates an http.Server and returns it. Keep the returned server so you can close it on shutdown.
- Keep-alive: one TCP connection carries many requests. Behind a load balancer, the Node keep-alive timeout should be longer than the load balancer's idle timeout, or the balancer may reuse a connection Node already closed and return a 502.
The red pen
Common traps: mistake → fix
Mistake: Express replaces Node's http server
Fix: an Express app is just a request handler function passed to http.createServer.
Mistake: Calling res.json twice sends two responses
Fix: the second call throws 'Cannot set headers after they are sent'.
Mistake: The request body is ready when the handler runs
Fix: in plain Node it arrives as a stream; you must read it (Express body parsers do this for you).
Easy to hard
Questions interviewers ask, easy to hard
- Write a JSON endpoint using only the http module.
- What does Express add on top of http?
- Why do you get 'Cannot set headers after they are sent to the client'?
- Random 502 errors behind a load balancer: how can keep-alive timeouts cause them?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.