Tsallaka zuwa abun ciki
Justice Tech School

A Basic HTTP Server

http.createServer handles requests. Here we start a server, call it once and close.

Example
const http = require("http");
const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello from " + req.url);
});
server.listen(0, () => {
  http.get({ port: server.address().port, path: "/hi" }, (res) => {
    let d = ""; res.on("data", (c) => (d += c));
    res.on("end", () => { console.log(res.statusCode, d); server.close(); });
  });
});

Result

200 Hello from /hi

Exercise

Start listening.

server.(3000)

Quiz Test

What does res.end do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.