Node.js HTTP Module

The http module is a built-in Node.js module that allows the creation of HTTP servers and clients. It is the foundation for building web servers, APIs, and web applications in Node.js. Every time a browser visits a webpage or an app sends a request to a server, it is using the HTTP protocol — and Node.js's http module handles that communication.

What Is HTTP?

HTTP stands for HyperText Transfer Protocol. It is the standard protocol (set of rules) used for transferring data between a client (like a web browser) and a server. When a user visits a website, the browser sends an HTTP request, and the server responds with an HTTP response containing the webpage content.

How a Node.js HTTP Server Works

  1. A server is created using http.createServer().
  2. The server listens on a specific port — a numbered doorway through which traffic enters.
  3. Every time a request arrives, a callback function is triggered.
  4. Inside the callback, the response is built and sent back to the client.

Creating the Simplest HTTP Server

// server.js
const http = require('http');

const server = http.createServer(function(req, res) {
  res.write("Hello from Node.js Server!");
  res.end();
});

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

Run this file with node server.js, then open a browser and go to http://localhost:3000. The browser will display:

Hello from Node.js Server!

Understanding req and res

The callback passed to createServer() receives two parameters:

  • req (Request Object): Contains information about the incoming request — the URL, HTTP method, headers, and body.
  • res (Response Object): Used to build and send the response back to the client — setting status codes, headers, and the response body.

Setting the HTTP Status Code and Headers

const http = require('http');

const server = http.createServer(function(req, res) {
  // Set status code and content type
  res.writeHead(200, { 'Content-Type': 'text/html' });

  // Send the response body
  res.end('

Welcome to My Node.js Server

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

res.writeHead(statusCode, headers) sets the HTTP status code (200 means OK) and any response headers. Content-Type: text/html tells the browser to render the response as HTML.

Handling Different Routes (URLs)

The req.url property holds the URL path that the client requested. This can be used to return different content for different paths:

const http = require('http');

const server = http.createServer(function(req, res) {
  res.writeHead(200, { 'Content-Type': 'text/html' });

  if (req.url === '/') {
    res.end('

Home Page

Welcome to the home page!

'); } else if (req.url === '/about') { res.end('

About Page

This is the about page.

'); } else if (req.url === '/contact') { res.end('

Contact Page

Reach us at hello@example.com

'); } else { res.writeHead(404, { 'Content-Type': 'text/html' }); res.end('

404 - Page Not Found

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

Handling Different HTTP Methods

req.method tells what type of HTTP method the client used (GET, POST, PUT, DELETE, etc.):

const http = require('http');

const server = http.createServer(function(req, res) {
  const method = req.method;
  const url = req.url;

  console.log("Method:", method, "| URL:", url);

  if (method === 'GET' && url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end("GET request received at /");
  } else if (method === 'POST' && url === '/data') {
    let body = '';

    req.on('data', function(chunk) {
      body += chunk.toString();
    });

    req.on('end', function() {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ received: body }));
    });
  } else {
    res.writeHead(405, { 'Content-Type': 'text/plain' });
    res.end("Method Not Allowed");
  }
});

server.listen(3000);

Serving JSON Responses

Node.js servers are commonly used to build APIs that return JSON data:

const http = require('http');

const users = [
  { id: 1, name: "Alice", role: "admin" },
  { id: 2, name: "Bob", role: "user" },
  { id: 3, name: "Charlie", role: "user" }
];

const server = http.createServer(function(req, res) {
  if (req.url === '/api/users' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(users));
  } else {
    res.writeHead(404, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: "Route not found" }));
  }
});

server.listen(3000, function() {
  console.log("API server running at http://localhost:3000");
});

Visit http://localhost:3000/api/users in the browser or with a tool like Postman to see the JSON response.

Reading Request Headers

const http = require('http');

const server = http.createServer(function(req, res) {
  console.log("Request Headers:");
  console.log(req.headers);

  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end("Check the terminal for request headers.");
});

server.listen(3000);

Common HTTP Status Codes

CodeMeaningWhen to Use
200OKRequest was successful.
201CreatedA new resource was successfully created.
400Bad RequestThe request was malformed or missing data.
401UnauthorizedAuthentication is required.
403ForbiddenAccess is denied even with authentication.
404Not FoundThe requested resource does not exist.
500Internal Server ErrorSomething went wrong on the server.

Key Points

  • The http module is built into Node.js and enables creating web servers without any external packages.
  • Servers are created with http.createServer(callback) and started with server.listen(port).
  • The callback receives req (request) and res (response) objects.
  • req.url holds the path; req.method holds the HTTP method (GET, POST, etc.).
  • res.writeHead() sets the status code and headers; res.end() sends the response.
  • JSON is returned by setting Content-Type: application/json and using JSON.stringify().
  • For real-world APIs and web servers, the Express.js framework (covered next) is used on top of the http module to simplify routing and middleware.

Leave a Comment

Your email address will not be published. Required fields are marked *