codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🟢

Node.js

7 / 63 topics
6Node.js File System7HTTP Module8Node.js Events9Streams10Buffers11Path Module12OS Module
Tutorials/Node.js/HTTP Module
🟢Node.js

HTTP Module

Updated 2026-04-20
4 min read

Introduction

The HTTP module is one of the core modules provided by Node.js, enabling you to create web servers and clients. It allows you to handle HTTP requests and responses directly using JavaScript. This tutorial will cover how to use the HTTP module to build a simple web server and client.

Understanding the HTTP Module

Node.js provides an http module that can be used to create both HTTP servers and clients. The module is built on top of the event-driven, non-blocking I/O model that makes Node.js highly efficient for handling multiple connections simultaneously.

Key Concepts

  • Server: A server listens for incoming requests from clients.
  • Client: A client sends requests to a server and receives responses.
  • Request: An HTTP request sent by a client to the server.
  • Response: An HTTP response sent by the server back to the client.

Creating an HTTP Server

To create an HTTP server using the http module, you need to use the createServer method. This method takes a callback function that is executed every time a request is received. The callback function receives two arguments: request and response.

Example Code

const http = require('http');

// Create an HTTP server
const server = http.createServer((req, res) => {
  // Set the response header to plain text
  res.writeHead(200, { 'Content-Type': 'text/plain' });

  // Send a response back to the client
  res.end('Hello, World!\n');
});

// Listen on port 3000
server.listen(3000, () => {
  console.log('Server is running at http://localhost:3000/');
});

Explanation

  1. Import the HTTP Module: const http = require('http');
  2. Create Server: const server = http.createServer((req, res) => { ... });
    • The callback function receives two parameters: req (request object) and res (response object).
  3. Set Response Header: res.writeHead(200, { 'Content-Type': 'text/plain' });
    • This sets the HTTP status code to 200 (OK) and the content type to plain text.
  4. Send Response: res.end('Hello, World!\n');
    • This sends the response back to the client.
  5. Listen on Port: server.listen(3000, () => { ... });
    • The server listens for incoming requests on port 3000.

Handling Different Routes

To handle different routes in your server, you can check the request URL and respond accordingly.

Example Code

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Home Page\n');
  } else if (req.url === '/about') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('About Page\n');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found\n');
  }
});

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

Explanation

  • Check Request URL: if (req.url === '/') { ... }
    • This checks the URL of the incoming request and responds accordingly.
  • 404 Not Found: If the URL does not match any defined routes, a 404 response is sent.

Handling POST Requests

To handle POST requests, you need to read the request body since it can contain data sent by the client.

Example Code

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/submit') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString(); // Convert Buffer to string
    });
    req.on('end', () => {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end(`Received: ${body}\n`);
    });
  } else {
    res.writeHead(405, { 'Content-Type': 'text/plain' });
    res.end('Method Not Allowed\n');
  }
});

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

Explanation

  • Check Request Method: if (req.method === 'POST' && req.url === '/submit') { ... }
    • This checks if the request method is POST and the URL is /submit.
  • Read Request Body:
    • req.on('data', chunk => { body += chunk.toString(); }); reads the incoming data chunks.
    • req.on('end', () => { ... }); is called when all data has been received.

Creating an HTTP Client

Node.js also allows you to create HTTP clients using the http module. This can be useful for making requests to external APIs or other servers.

Example Code

const http = require('http');

// Options object
const options = {
  hostname: 'example.com',
  port: 80,
  path: '/',
  method: 'GET'
};

// Create a request
const req = http.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`);

  let data = '';
  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log(data);
  });
});

req.on('error', (error) => {
  console.error(`Problem with request: ${error.message}`);
});

// End the request
req.end();

Explanation

  1. Options Object:
    • hostname: The domain name of the server.
    • port: The port number on which the server is listening.
    • path: The path to the resource you want to access.
    • method: The HTTP method (GET, POST, etc.).
  2. Create Request: const req = http.request(options, (res) => { ... });
    • This creates a request object with the specified options.
  3. Handle Response:
    • res.on('data', (chunk) => { data += chunk; }); reads the response data chunks.
    • res.on('end', () => { console.log(data); }); is called when all data has been received.
  4. Error Handling:
    • req.on('error', (error) => { ... }); handles any errors that occur during the request.
  5. End Request: req.end();
    • This ends the request and sends it to the server.

Best Practices

  • Use HTTPS for Secure Communication: Always use HTTPS instead of HTTP to secure data transmission.
  • Handle Errors Gracefully: Implement proper error handling to manage unexpected situations.
  • Optimize Performance: Use efficient algorithms and data structures to handle large volumes of requests.
  • Keep Dependencies Updated: Regularly update dependencies to ensure security and performance improvements.

Conclusion

The HTTP module in Node.js is a powerful tool for building web servers and clients. By understanding how to create and manage HTTP servers, as well as making HTTP requests, you can build robust and efficient applications. This tutorial has covered the basics of using the HTTP module, including creating servers, handling different routes, managing POST requests, and creating clients. With this knowledge, you can start building your own web applications in Node.js.


PreviousNode.js File SystemNext Node.js Events

Recommended Gear

Node.js File SystemNode.js Events