Node.js HTTP Server
Node can build a web server with no extra packages. Here the server starts, a request is made to it, and then it shuts down so the example finishes.
ExampleNode.js
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/hello") {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, client!");
} else if (req.url === "/json") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, path: req.url, method: req.method }));
} else {
res.writeHead(404);
res.end("Not found");
}
});
server.listen(0, async () => {
const port = server.address().port;
for (const path of ["/hello", "/json", "/missing"]) {
const r = await fetch(`http://localhost:${port}${path}`);
console.log(r.status, await r.text());
}
server.close();
});Output
200 Hello, client!
200 {"ok":true,"path":"/json","method":"GET"}
404 Not foundlisten(0) picks any free port. A real server would use a fixed one such as 3000 and keep running. The handler receives the request (req) and writes the response (res).
Quick check
Which two objects does an HTTP handler receive?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.