← Back to Node.js Course | Chapter 6: HTTP Module | Lesson 2 of 7

Requests को Handle करना

request object आपको बताता है method, URL, headers, और body जो client ने भेजी।
Syntax
javascript
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

javascript
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. #}
आम गलतियां
  1. यह भूल जाना कि body एक stream है
  2. गलत case से headers compare करना
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.