http
The http
module provides utilities to create HTTP servers and clients. It supports request/response streaming, headers, and status codes.
API Surface
Server
http.createServer([options], requestListener)
— create an HTTP server.- server.listen(port[, host], callback) — start listening.
- request (IncomingMessage):
req.method
,req.url
,req.headers
req.on("data")
,req.on("end")
- response (ServerResponse):
res.statusCode
,res.setHeader(name, value)
res.write(data)
,res.end([data])
Client
http.request(options, callback)
— create HTTP request.http.get(options, callback)
— shortcut for GET.- ClientRequest:
.write()
,.end()
. - IncomingMessage: stream for response body.
Examples (English only)
const http = require("http");
// Simple HTTP server
const server = http.createServer((req, res) => {
console.log(req.method, req.url);
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello World\n");
});
server.listen(3000, () => console.log("Server running on port 3000"));
// Simple HTTP client GET
http.get("http://localhost:3000", (res) => {
console.log("status:", res.statusCode);
res.on("data", (chunk) => console.log("body:", chunk.toString()));
});
Notes
- Responses must be explicitly ended with
res.end()
. - Always set proper headers (e.g.,
Content-Type
) for clients. - Request and response bodies are streams; handle
'data'
and'end'
. - For HTTPS, use the separate
https
module.