Creating an HTTP Server
http.createServer
Section titled “http.createServer”http.createServer(callback) returns a Server instance. The callback — called the request listener — is invoked once per incoming HTTP request. It receives two arguments:
req— anIncomingMessageobject describing the request (method, URL, headers, body stream).res— aServerResponseobject used to write the response.
Call server.listen(port, callback) to start accepting connections. The callback fires once the server is ready.
Status codes and headers
Section titled “Status codes and headers”Every HTTP response has a status code and a set of headers. Use res.writeHead(statusCode, headersObject) to set both at once, before writing any body data.
Common status codes:
| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 400 | Bad Request |
| 404 | Not Found |
| 500 | Internal Server Error |
res.end — sending the response body
Section titled “res.end — sending the response body”res.end(data) writes the final chunk of the response body and signals to Node.js that the response is complete. Every request handler must call res.end() (or res.destroy()) — if you forget, the client will wait forever and the connection will time out.
You can also use res.write(data) to send data in chunks before calling res.end().
A complete server with status codes and headers
Section titled “A complete server with status codes and headers”Needs the Node.js runtime — open in StackBlitz to run.
Open in StackBlitz, then visit http://localhost:3000 in the preview tab to see the rendered HTML response with correct headers.
Responding with different status codes
Section titled “Responding with different status codes”Needs the Node.js runtime — open in StackBlitz to run.