Lesson 17 of 50 – HTTP Module
34% Completed
34%

Node.js HTTP Module

The Node.js HTTP module allows us to create web servers and handle HTTP requests and responses. It is a built-in module, so we do not need to install an external package to use it.

In simple words: The HTTP module helps a Node.js application receive requests from browsers and send responses back to them.

1. What Is the HTTP Module?

HTTP stands for Hypertext Transfer Protocol. It is used for communication between a client, such as a browser, and a server.

How HTTP Communication Works
  1. A user opens a website in a browser.
  2. The browser sends an HTTP request to the server.
  3. The Node.js server processes the request.
  4. The server sends an HTTP response.
  5. The browser displays the response.
Browser
   |
   | HTTP Request
   v
Node.js HTTP Server
   |
   | HTTP Response
   v
Browser Displays Result

2. Import the HTTP Module

Node.js provides the HTTP module by default. We can import it using the require() function in CommonJS.

Example: Import HTTP
const http = require('http');

console.log('HTTP module loaded successfully.');
Output:
HTTP module loaded successfully.

The http variable now provides methods for creating HTTP servers and making HTTP requests.

3. Create Your First HTTP Server

We can create a server using the http.createServer() method.

Example: Hello World Server
const http = require('http');

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

server.listen(3000, function () {
    console.log('Server running at http://localhost:3000');
});
Terminal Output:
Server running at http://localhost:3000
Browser Output:
Hello World from Node.js!
Important: Save this code as server.js, run node server.js, and open http://localhost:3000 in your browser. Keep the terminal running while testing.

4. Understanding req and res

The callback passed to createServer() receives two important objects: req and res.

Object Full Name Purpose
req Request Contains information about the incoming request.
res Response Used to send a response to the client.
Example: Request Method and URL
const http = require('http');

const server = http.createServer(function (req, res) {
    res.setHeader('Content-Type', 'text/plain');

    res.end(
        'Method: ' + req.method +
        '\nURL: ' + req.url
    );
});

server.listen(3000, function () {
    console.log('Server started on port 3000');
});

Open http://localhost:3000/about.

Browser Output:
Method: GET
URL: /about

req.method gives the HTTP method, while req.url gives the requested path and query string.

5. Send an HTML Response

We can send HTML content from the server by setting the response content type to text/html.

Example: Display HTML
const http = require('http');

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

    res.end(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>My Node.js Website</title>
        </head>
        <body>
            <h1>Welcome to Soopro Pathshala</h1>
            <p>This page is served by Node.js.</p>
        </body>
        </html>
    `);
});

server.listen(3000, function () {
    console.log('Open http://localhost:3000');
});
Browser Output:

Welcome to Soopro Pathshala

This page is served by Node.js.

6. Understanding HTTP Status Codes

An HTTP status code tells the client whether a request was successful or whether something went wrong.

Status Code Meaning
200 OK — the request succeeded.
201 Created — a resource was created.
400 Bad Request — the request is invalid.
401 Unauthorized — authentication is required or invalid.
404 Not Found — the requested resource was not found.
500 Internal Server Error — the server encountered an error.
Example: Set a Status Code
const http = require('http');

const server = http.createServer(function (req, res) {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');

    res.end('Request successful!');
});

server.listen(3000);

The statusCode property sets the response status code. The example sends 200 OK.

7. Handle Different Routes

We can check req.url to return different responses for different paths. This is a simple way to understand routing before learning Express.js.

Example: Home, About and Contact
const http = require('http');

const server = http.createServer(function (req, res) {
    res.setHeader('Content-Type', 'text/plain; charset=utf-8');

    if (req.url === '/') {
        res.statusCode = 200;
        res.end('Welcome to the Home Page');
    } else if (req.url === '/about') {
        res.statusCode = 200;
        res.end('This is the About Page');
    } else if (req.url === '/contact') {
        res.statusCode = 200;
        res.end('This is the Contact Page');
    } else {
        res.statusCode = 404;
        res.end('404 - Page Not Found');
    }
});

server.listen(3000, function () {
    console.log('Server running on port 3000');
});
Test These URLs:
  • http://localhost:3000/
  • http://localhost:3000/about
  • http://localhost:3000/contact
  • http://localhost:3000/xyz
For larger applications, Express.js provides a more convenient routing system.

8. Using write() and end()

The write() method sends part of a response. The end() method finishes the response. You can call end() without write() when you want to send a single response body.

Example: Multiple Response Parts
const http = require('http');

const server = http.createServer(function (req, res) {
    res.setHeader('Content-Type', 'text/plain');

    res.write('Hello ');
    res.write('Students!');
    res.end();
});

server.listen(3000);
Browser Output:
Hello Students!
Call end() when the response is complete. Do not try to write additional data after ending the response.

9. Important HTTP Server Methods

Method or Property Purpose
http.createServer() Creates an HTTP server.
server.listen() Starts listening on a port or address.
req.method Provides the incoming HTTP method, such as GET or POST.
req.url Provides the request path and query string.
res.statusCode Sets or reads the response status code.
res.setHeader() Sets a response header.
res.write() Writes a response body chunk.
res.end() Completes the response.

📝 Practical Assignment

Create a Simple Website Server
Create a Node.js program using the HTTP module that meets the following requirements:
  1. Create a server on port 3000.
  2. Display a welcome message on the home page.
  3. Create an /about route.
  4. Create a /courses route that displays your course names.
  5. Return status code 404 for unknown routes.
  6. Set the correct content type for each response.

Challenge: Display the request method and URL on a separate route.


🧠 Quiz – HTTP Module

Select the correct answer for each question.

1. Which method creates an HTTP server?

2. Which object is used to send a response to the client?

3. Which status code means that a page was not found?