Creating HTTP server
http.createServer gives you a server that runs your function for every incoming request.
In this page:
Syntax
const http = require('http');
const server = http.createServer((req, res) => {
res.end('response');
});
server.listen(port);
Creating HTTP server
createServer takes a request listener, and listen starts it on a port. Each request runs the listener with request and response objects. The example starts a server, calls it once and shuts down so it can run as a script.
Note:
Port 0 asks the OS for any free port.
Example: 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
- Forgetting to call listen
- Never ending the response
- Port already in use errors
Chapter Summary
- createServer takes a listener
- listen binds a port
- Each request calls the listener
- Always end the response
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: