Requests को Handle करना
request object आपको बताता है method, URL, headers, और body जो client ने भेजी।
In this page:
Syntax
http.createServer((req, res) => {
req.method;
req.url;
req.headers['header-name'];
});
Requests Handle करना
req.method और req.url action और path identify करते हैं, req.headers lowercase header names hold करता है, और body data और end सुनकर आप पढ़ते एक stream की तरह आता है। Manually route करने के लिए method और URL पर branch करें।
Note:
req.headers में Header names lowercase होते हैं।
उदाहरण: 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/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- यह भूल जाना कि body एक stream है
- गलत case से headers compare करना
- body size limit न करना
चैप्टर सारांश
- req.method और req.url requests route करते हैं
- Headers lowercase हैं
- Body एक stream की तरह आती है
- Body sizes limit करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: