HTTP Module - Handling Different Types of Requests

HTTP Module - Handling Different Types of Requests

HTTP Module - Handling Different Types of Requests

Introduction

Node.js is a powerful JavaScript runtime that enables server-side development. One of its core modules is the http module, which allows developers to create web servers and handle HTTP requests and responses directly without relying on external libraries like Express.js. This gives you full control and transparency over how the server behaves and responds to different HTTP request methods such as GET, POST, PUT, DELETE, and others.

In this document, we will cover how to use the http module to build a basic server and then handle different types of requests, including parsing incoming data, sending appropriate responses, handling routes, managing headers, and maintaining proper HTTP status codes.

Getting Started with the HTTP Module

The http module is built into Node.js. You don’t need to install it separately.

Creating a Basic HTTP Server

const http = require('http');

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

server.listen(3000, () => {
    console.log('Server listening on port 3000');
});

Understanding Request Methods

HTTP defines several methods for client-server communication. The most common ones include:

  • GET: Retrieve data from the server.
  • POST: Submit data to the server.
  • PUT: Replace existing resource with new data.
  • DELETE: Remove a resource from the server.
  • PATCH: Apply partial modifications.

Routing Based on Request Method and URL

Basic Method and URL Routing

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.method === 'GET' && req.url === '/') {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Home Page');
    } else if (req.method === 'POST' && req.url === '/submit') {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Data Submitted');
    } else {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        res.end('Not Found');
    }
});

server.listen(3000, () => {
    console.log('Server running on port 3000');
});

Handling GET Requests

GET is the most basic and commonly used HTTP method. It's used to request data from the server.

Example: Handling a GET request

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.method === 'GET' && req.url === '/info') {
        res.writeHead(200, {'Content-Type': 'application/json'});
        const data = { message: 'This is a GET response' };
        res.end(JSON.stringify(data));
    }
});

server.listen(3000);

Handling POST Requests

POST requests are used to send data to the server. This is often done when submitting forms or uploading files.

Parsing POST Data

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();
        });

        req.on('end', () => {
            console.log('Received Data:', body);
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end('Data received');
        });
    }
});

server.listen(3000);

Handling PUT Requests

PUT requests are used to update or replace resources. Similar to POST, PUT usually includes a request body.

Example: Updating a resource

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.method === 'PUT' && req.url === '/update') {
        let body = '';

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

        req.on('end', () => {
            console.log('Updated Data:', body);
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end('Resource updated');
        });
    }
});

server.listen(3000);

Handling DELETE Requests

DELETE requests are used to delete a resource on the server.

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.method === 'DELETE' && req.url === '/delete') {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Resource deleted');
    }
});

server.listen(3000);

Using URL Module for Query Parameters

You can use the built-in URL module to parse query strings from a GET request.

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);

    if (req.method === 'GET' && parsedUrl.pathname === '/search') {
        const query = parsedUrl.query;
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(JSON.stringify(query));
    }
});

server.listen(3000);

Setting HTTP Headers

HTTP headers give clients and servers information about the request and response. Examples include content type, length, cache settings, etc.

res.writeHead(200, {
    'Content-Type': 'application/json',
    'Cache-Control': 'no-cache'
});

Using Status Codes

Status codes are crucial for client-server communication.

  • 200 - OK
  • 201 - Created
  • 400 - Bad Request
  • 404 - Not Found
  • 500 - Internal Server Error

Example with status codes

if (!data) {
    res.writeHead(400, {'Content-Type': 'text/plain'});
    res.end('Missing Data');
}

Serving HTML Content

const fs = require('fs');
const http = require('http');

const server = http.createServer((req, res) => {
    if (req.method === 'GET' && req.url === '/') {
        fs.readFile('index.html', (err, data) => {
            if (err) {
                res.writeHead(500, {'Content-Type': 'text/plain'});
                res.end('Server error');
            } else {
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.end(data);
            }
        });
    }
});

server.listen(3000);

Handling JSON Data

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.method === 'POST' && req.url === '/json') {
        let body = '';

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

        req.on('end', () => {
            const parsed = JSON.parse(body);
            res.writeHead(200, {'Content-Type': 'application/json'});
            res.end(JSON.stringify({ received: parsed }));
        });
    }
});

server.listen(3000);

Organizing Routes Using Functions

function handleGet(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('GET route');
}

function handlePost(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('POST route');
}

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.method === 'GET') return handleGet(req, res);
    if (req.method === 'POST') return handlePost(req, res);

    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Route not found');
});

server.listen(3000);

Security Tips

  • Always validate user input before processing
  • Use HTTPS for secure data transfer
  • Set proper CORS headers if building APIs

Logging Requests

const http = require('http');

const server = http.createServer((req, res) => {
    console.log(`${req.method} ${req.url}`);
    res.writeHead(200);
    res.end('Logged');
});

server.listen(3000);

The HTTP module in Node.js gives you a low-level and powerful interface to handle different types of HTTP requests without relying on external frameworks. This allows for complete control over routing, request parsing, response formatting, and status code handling. While modern applications often use higher-level frameworks like Express, understanding how the core http module works is essential for building lightweight, efficient, and flexible services.

By mastering the handling of GET, POST, PUT, DELETE, and other HTTP methods, parsing query strings and body content, and returning meaningful responses with the correct headers and status codes, you can build powerful and scalable HTTP servers using nothing but Node.js and the built-in http module.

Beginner 5 Hours
HTTP Module - Handling Different Types of Requests

HTTP Module - Handling Different Types of Requests

Introduction

Node.js is a powerful JavaScript runtime that enables server-side development. One of its core modules is the http module, which allows developers to create web servers and handle HTTP requests and responses directly without relying on external libraries like Express.js. This gives you full control and transparency over how the server behaves and responds to different HTTP request methods such as GET, POST, PUT, DELETE, and others.

In this document, we will cover how to use the http module to build a basic server and then handle different types of requests, including parsing incoming data, sending appropriate responses, handling routes, managing headers, and maintaining proper HTTP status codes.

Getting Started with the HTTP Module

The http module is built into Node.js. You don’t need to install it separately.

Creating a Basic HTTP Server

const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World\n'); }); server.listen(3000, () => { console.log('Server listening on port 3000'); });

Understanding Request Methods

HTTP defines several methods for client-server communication. The most common ones include:

  • GET: Retrieve data from the server.
  • POST: Submit data to the server.
  • PUT: Replace existing resource with new data.
  • DELETE: Remove a resource from the server.
  • PATCH: Apply partial modifications.

Routing Based on Request Method and URL

Basic Method and URL Routing

const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'GET' && req.url === '/') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Home Page'); } else if (req.method === 'POST' && req.url === '/submit') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Data Submitted'); } else { res.writeHead(404, {'Content-Type': 'text/plain'}); res.end('Not Found'); } }); server.listen(3000, () => { console.log('Server running on port 3000'); });

Handling GET Requests

GET is the most basic and commonly used HTTP method. It's used to request data from the server.

Example: Handling a GET request

const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'GET' && req.url === '/info') { res.writeHead(200, {'Content-Type': 'application/json'}); const data = { message: 'This is a GET response' }; res.end(JSON.stringify(data)); } }); server.listen(3000);

Handling POST Requests

POST requests are used to send data to the server. This is often done when submitting forms or uploading files.

Parsing POST Data

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(); }); req.on('end', () => { console.log('Received Data:', body); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Data received'); }); } }); server.listen(3000);

Handling PUT Requests

PUT requests are used to update or replace resources. Similar to POST, PUT usually includes a request body.

Example: Updating a resource

const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'PUT' && req.url === '/update') { let body = ''; req.on('data', chunk => { body += chunk; }); req.on('end', () => { console.log('Updated Data:', body); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Resource updated'); }); } }); server.listen(3000);

Handling DELETE Requests

DELETE requests are used to delete a resource on the server.

const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'DELETE' && req.url === '/delete') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Resource deleted'); } }); server.listen(3000);

Using URL Module for Query Parameters

You can use the built-in URL module to parse query strings from a GET request.

const http = require('http'); const url = require('url'); const server = http.createServer((req, res) => { const parsedUrl = url.parse(req.url, true); if (req.method === 'GET' && parsedUrl.pathname === '/search') { const query = parsedUrl.query; res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify(query)); } }); server.listen(3000);

Setting HTTP Headers

HTTP headers give clients and servers information about the request and response. Examples include content type, length, cache settings, etc.

res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' });

Using Status Codes

Status codes are crucial for client-server communication.

  • 200 - OK
  • 201 - Created
  • 400 - Bad Request
  • 404 - Not Found
  • 500 - Internal Server Error

Example with status codes

if (!data) { res.writeHead(400, {'Content-Type': 'text/plain'}); res.end('Missing Data'); }

Serving HTML Content

const fs = require('fs'); const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'GET' && req.url === '/') { fs.readFile('index.html', (err, data) => { if (err) { res.writeHead(500, {'Content-Type': 'text/plain'}); res.end('Server error'); } else { res.writeHead(200, {'Content-Type': 'text/html'}); res.end(data); } }); } }); server.listen(3000);

Handling JSON Data

const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'POST' && req.url === '/json') { let body = ''; req.on('data', chunk => { body += chunk; }); req.on('end', () => { const parsed = JSON.parse(body); res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify({ received: parsed })); }); } }); server.listen(3000);

Organizing Routes Using Functions

function handleGet(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('GET route'); } function handlePost(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('POST route'); } const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'GET') return handleGet(req, res); if (req.method === 'POST') return handlePost(req, res); res.writeHead(404, {'Content-Type': 'text/plain'}); res.end('Route not found'); }); server.listen(3000);

Security Tips

  • Always validate user input before processing
  • Use HTTPS for secure data transfer
  • Set proper CORS headers if building APIs

Logging Requests

const http = require('http'); const server = http.createServer((req, res) => { console.log(`${req.method} ${req.url}`); res.writeHead(200); res.end('Logged'); }); server.listen(3000);

The HTTP module in Node.js gives you a low-level and powerful interface to handle different types of HTTP requests without relying on external frameworks. This allows for complete control over routing, request parsing, response formatting, and status code handling. While modern applications often use higher-level frameworks like Express, understanding how the core http module works is essential for building lightweight, efficient, and flexible services.

By mastering the handling of GET, POST, PUT, DELETE, and other HTTP methods, parsing query strings and body content, and returning meaningful responses with the correct headers and status codes, you can build powerful and scalable HTTP servers using nothing but Node.js and the built-in http module.

Related Tutorials

Frequently Asked Questions for Node.js

A function passed as an argument and executed later.

Runs multiple instances to utilize multi-core systems.

Reusable blocks of code, exported and imported using require() or import.

nextTick() executes before setImmediate() in the event loop.

Starts a server and listens on specified port.

Node Package Manager β€” installs, manages, and shares JavaScript packages.

A minimal and flexible web application framework for Node.js.

A stream handles reading or writing data continuously.

It processes asynchronous callbacks and non-blocking I/O operations efficiently.

Node.js is a JavaScript runtime built on Chrome's V8 engine for server-side scripting.

An object representing the eventual completion or failure of an asynchronous operation.

require is CommonJS; import is ES6 syntax (requires transpilation or newer versions).

Use module.exports or exports.functionName.

Variables stored outside the code for configuration, accessed using process.env.


MongoDB, often used with Mongoose for schema management.

Describes project details and manages dependencies and scripts.

Synchronous blocks execution; asynchronous runs in background without blocking.

Allows or restricts resources shared between different origins.

Use try-catch, error events, or middleware for error handling.

Provides file system-related operations like read, write, delete.

Using event-driven architecture and non-blocking I/O.

Functions in Express that execute during request-response cycle.

A set of routes or endpoints to interact with server logic or databases.

Yes, it's single-threaded but handles concurrency using the event loop and asynchronous callbacks.

Middleware to parse incoming request bodies, like JSON or form data.

line

Copyrights © 2024 letsupdateskills All rights reserved