Responses भेजना
response object आपको वापस भेजे जाने वाले status, headers, और body set करने देता है।
In this page:
Syntax
res.writeHead(statusCode, { 'Content-Type': 'type' });
res.write('chunk');
res.end('body');
Responses भेजना
res.writeHead(status, headers) या res.statusCode और res.setHeader metadata set करते हैं, और res.end(body) response खत्म करता है। JSON के लिए, Content-Type को application/json set करें और data stringify करें।
Note:
body लिखने से पहले headers set करें।
उदाहरण: Sending responses
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, path: req.url }));
});
server.listen(0, () => {
http.get({ port: server.address().port, path: "/api" }, (res) => {
console.log(res.statusCode, res.headers["content-type"]);
res.on("data", (c) => console.log(String(c)));
res.on("end", () => server.close());
});
});
// Output:
// 200 application/json
// {"ok":true,"path":"/api"}
⚠️ 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 शुरू होने के बाद headers set करना
- Content-Type भूल जाना
- end दो बार call करना
चैप्टर सारांश
- writeHead status और headers set करता है
- end body भेजता है
- JSON को Content-Type चाहिए
- पहले headers set करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: