HTTP Server बनाना
http.createServer आपको एक server देता है जो हर incoming request के लिए आपका function चलाता है।
In this page:
Syntax
const http = require('http');
const server = http.createServer((req, res) => {
res.end('response');
});
server.listen(port);
HTTP Server बनाना
createServer एक request listener लेता है, और listen इसे एक port पर शुरू करता है। हर request request और response objects के साथ listener चलाता है। Example एक server शुरू करता है, इसे एक बार call करता है, और shut down करता है ताकि यह एक script की तरह चल सके।
Note:
Port 0 OS से कोई भी free port माँगता है।
उदाहरण: Creating HTTP server
const http = require("http");
const server = http.createServer((req, res) => {
res.end("Hello from Node");
});
server.listen(0, () => {
const { port } = server.address();
http.get({ port }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => { console.log("server said:", body); server.close(); });
});
});
// Output:
// server said: Hello from Node
⚠️ 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. #}
आम गलतियां
- listen call करना भूल जाना
- response कभी खत्म न करना
- Port already in use जैसी errors आना
चैप्टर सारांश
- createServer एक listener लेता है
- listen एक port bind करता है
- हर request listener call करती है
- हमेशा response खत्म करें
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: