Beginner Fundamentals

The http Module

The http module lets you build web servers without any external library. It is the foundation that frameworks like Express are built on.

Creating a server

const http = require("http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello, World!");
});

server.listen(3000, () => {
  console.log("Server running at http://localhost:3000");
});

Run it and open http://localhost:3000 in a browser.

The request and response

  • req holds information about the incoming request, like req.url and req.method.
  • res is how you answer: set the status, headers, and body.

Simple routing

const http = require("http");

http.createServer((req, res) => {
  if (req.url === "/about") {
    res.end("About page");
  } else {
    res.end("Home page");
  }
}).listen(3000);

Summary

With http.createServer you can serve responses based on the URL. It is the simplest way to build a server in Node.js.