What is Node.js HTTP Module and How to Use

The HTTP module, a core component of Node.js, provides the tools necessary to create web servers and handle HTTP requests and responses.

It simplifies the process of creating web servers and handling HTTP protocols. To begin using it, include the module in your script:

const http = require('http');

Creating a Simple Web Server

Creating a basic web server in Node.js involves using the http.createServer() method to handle incoming HTTP requests. Here’s an example:

const http = require('http');

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

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

In this example, the server responds with a “Hello, Node.js!” message for every incoming request.

Handling HTTP Methods

The HTTP module supports various HTTP methods, such as GET, POST, PUT, and DELETE. You can determine the method used in a request by accessing the req.method property. Here’s an example of handling different HTTP methods:

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('This is a GET request.');
    } else if (req.method === 'POST') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('This is a POST request.');
    } else {
        res.writeHead(405, { 'Content-Type': 'text/plain' });
        res.end('Method Not Allowed');
    }
});

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

In this example, the server responds differently based on the HTTP method used in the request.

Working with Routes

While the HTTP module provides a basic foundation for handling requests, building more complex web applications often involves implementing a routing system. You can achieve this by examining the req.url property and defining routes accordingly. Here’s a simple example:

const http = require('http');

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

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

In this example, different routes are defined for the home page (/), about page (/about), and an error message for other paths.

Understanding Request and Response Objects

The req and res objects provided to the request handler function carry important information about the incoming request and allow you to send a response back to the client.

const server = http.createServer((req, res) => {

});

Request Object (req)

The req object contains information about the incoming HTTP request, such as the request method (req.method), request URL (req.url), and request headers (req.headers). You can use this information to make decisions in your server logic.

Response Object (res)

The res object is used to send a response back to the client. You can set response headers using res.writeHead(), write the response body using res.write(), and end the response using res.end(). The status code, content type, and other response headers can be configured using these methods.