Node.js Fundamentals

Learn Node.js from scratch including core concepts, modules, and basic server development.

beginner Backend Development 5 hours

Chapter 7: HTTP Module

Chapter 7 of 15

Chapter 7: HTTP Module

7.1 HTTP Requests

The http module can also make HTTP requests to other servers, not just create servers.

const http = require('http');

// Make GET request
const options = {
    hostname: 'api.example.com',
    port: 80,
    path: '/users',
    method: 'GET'
};

const req = http.request(options, (res) => {
    let data = ';
    
    // Receive response data
    res.on('data', (chunk) => {
        data += chunk;
    });
    
    // Process complete response
    res.on('end', () => {
        console.log(JSON.parse(data));
    });
});

req.on('error', (err) => {
    console.error('Request error:', err);
});

req.end();

Using https Module:

const https = require('https');

// HTTPS request
https.get('https://api.github.com/users/octocat', (res) => {
    let data = ';
    res.on('data', chunk => data += chunk);
    res.on('end', () => console.log(JSON.parse(data)));
}).on('error', err => console.error(err));

POST Request:

const http = require('http');

const postData = JSON.stringify({ name: 'John', email: 'john@example.com' });

const options = {
    hostname: 'api.example.com',
    port: 80,
    path: '/users',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
    }
};

const req = http.request(options, (res) => {
    let data = ';
    res.on('data', chunk => data += chunk);
    res.on('end', () => console.log(data));
});

req.write(postData);
req.end();

7.2 Handling Routes

Create routing logic to handle different URLs and methods.

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

const routes = {
    'GET /': (req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end('<h1>Home</h1>');
    },
    'GET /about': (req, res) => {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end('<h1>About</h1>');
    },
    'GET /api/users': (req, res) => {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify([{ id: 1, name: 'John' }]));
    }
};

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);
    const route = `${req.method} ${parsedUrl.pathname}`;
    
    const handler = routes[route];
    if (handler) {
        handler(req, res);
    } else {
        res.writeHead(404);
        res.end('Not Found');
    }
});

server.listen(3000);

7.3 Query Parameters

Parse and use URL query parameters.

const url = require('url');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);
    const query = parsedUrl.query;
    
    // Access query parameters
    // URL: /search?q=nodejs&limit=10
    const searchTerm = query.q;
    const limit = parseInt(query.limit) || 10;
    
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ searchTerm, limit }));
});

7.4 HTTP Module Best Practices

Follow best practices when working with HTTP module.

  • Use https for secure connections
  • Handle errors properly
  • Set appropriate timeouts
  • Parse URLs correctly
  • Validate request data
  • Consider using libraries (axios, node-fetch) for complex requests