HTTP Server
http.createServer takes a handler that receives a request and response. Set a status code and headers, then end the response. Here the server starts, calls itself once and stops so the example finishes.
Example
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ path: req.url, ok: true }));
});
server.listen(0, async () => {
const { port } = server.address();
const r = await fetch(`http://127.0.0.1:${port}/hello`);
console.log(r.status, await r.json());
server.close();
});Result
200 { path: '/hello', ok: true }Exercise
Start listening.
server.(3000)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.