Handling requests
The request object tells you the method, URL, headers and body of what the client sent.
In this page:
Syntax
http.createServer((req, res) => {
req.method;
req.url;
req.headers['header-name'];
});
Handling requests
req.method and req.url identify the action and path, req.headers holds lowercase header names, and the body arrives as a stream you read by listening to data and end. Branch on method and URL to route manually.
Note:
Header names are lowercased in req.headers.
Example: Handling requests
const http = require("http");
const server = http.createServer((req, res) => {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => res.end(`${req.method} ${req.url} body=${body} ua=${req.headers["user-agent"] || "none"}`));
});
server.listen(0, () => {
const r = http.request({ port: server.address().port, method: "POST", path: "/echo?x=1", headers: { "user-agent": "demo" } }, (res) => {
res.on("data", (c) => console.log(String(c)));
res.on("end", () => server.close());
});
r.end("hi");
});
// Output:
// POST /echo?x=1 body=hi ua=demo
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Forgetting the body is a stream
- Comparing headers with wrong case
- Not limiting body size
Chapter Summary
- req.method and req.url route requests
- Headers are lowercase
- Body arrives as a stream
- Limit body sizes
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: