Creating an HTTP Server

Node.js provides the built-in node:http module for creating HTTP servers. An HTTP server receives a request and produces a response.

The request contains information such as the HTTP method, URL, headers, and body. The response controls the status code, headers, and response body.

Basic HTTP Server
import http from 'node:http';

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ message: 'Hello Node.js' }));
});

server.listen(3000, () => {
  console.log('Server running on port 3000');
});
💡 The server responds to every request with a JSON payload and listens on port 3000.
Key Takeaways
  • Node.js can create HTTP servers without Express.
  • The request and response objects expose HTTP-level functionality.
  • Frameworks such as Express build higher-level abstractions on top of Node HTTP capabilities.
Knowledge Check

Which built-in Node.js module creates HTTP servers?