Set headers with res.writeHead(status, headers) and send a body with res.end().
server.listen(3000)
In practice, frameworks like Express make routing much easier.
💡 Key Takeaways: Node.js HTTP Server
Mastering Node.js HTTP Server helps you write clean and reliable Node.js code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
Node.js HTTP Server Code Example
Node.js
import http from "node:http";
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Home</h1>");
} else if (req.url === "/api/time") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ time: new Date().toISOString() }));
} else {
res.writeHead(404);
res.end("Not found");
}
});
server.listen(3000, () => console.log("Server on http://localhost:3000"));
Output
Server on http://localhost:3000
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
Node.js HTTP Server Practice Exercises
Check what you learned in “Node.js HTTP Server”.
/ 2 solved
Fill in the blank
Create a server with the http module.
const server = http.((req, res) => { });
✓ Correct!Not quite. Try again.
Multiple choice
Which method sends the response body and finishes the response?