Node.js Tutorial – Day 5: Node.js HTTP Module and Creating a Server
5 mins read

Node.js Tutorial – Day 5: Node.js HTTP Module and Creating a Server

Welcome back to our Node.js Tutorial series! So far, we’ve explored:

In Day 5, we will dive into the HTTP module, which allows you to create web servers and handle HTTP requests and responses directly in Node.js, without any external framework.

This is the foundation of building APIs, websites, and full-stack applications in Node.js.


What is the HTTP Module in Node.js?

The HTTP module is a built-in Node.js module that lets you:

  • Create web servers
  • Handle client requests and server responses
  • Build REST APIs
  • Serve files and data over the internet

Since HTTP is the protocol of the web, mastering this module is crucial in any Node.js Tutorial.

To use it:

const http = require('http');

Creating Your First Node.js Server

Here’s a simple server that listens on port 3000:

const http = require('http');

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

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

Steps to run this server:

  1. Save the code in server.js.
  2. Run it:
node server.js
  1. Open browser → http://localhost:3000.
  2. You’ll see:
Hello, welcome to my Node.js Tutorial server!

Handling Requests and Responses

Every request has URL and method, and every response has a status code and headers.

Example:

const http = require('http');

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

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

✅ Now your server responds differently based on the URL path.


Serving JSON Data

You can also return JSON responses (important for APIs):

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.url === '/api' && req.method === 'GET') {
        const data = {
            name: "Node.js Tutorial",
            topic: "HTTP Module",
            version: "Day 5"
        };
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(data));
    }
});

server.listen(4000, () => {
    console.log('API server running at http://localhost:4000/api');
});

Go to http://localhost:4000/api → You’ll get JSON output.


Mini-Project: Simple Routing Server

Let’s build a mini web server with multiple routes:

const http = require('http');

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

    switch (req.url) {
        case '/':
            res.statusCode = 200;
            res.end('<h1>Welcome to Home Page</h1>');
            break;
        case '/contact':
            res.statusCode = 200;
            res.end('<h1>Contact Us at contact@example.com</h1>');
            break;
        case '/services':
            res.statusCode = 200;
            res.end('<h1>Our Services: Web Development, Node.js Training</h1>');
            break;
        default:
            res.statusCode = 404;
            res.end('<h1>404 Page Not Found</h1>');
    }
});

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

Now your server can serve multiple pages just like a basic website!


Advantages of Using HTTP Module

  • No external dependencies required.
  • Lightweight and simple to use.
  • Great for learning fundamentals of request-response handling.
  • Forms the base for advanced frameworks like Express.js.

Best Practices

  • Always set Content-Type headers correctly (text/html, application/json, etc.).
  • Use status codes (200, 404, 500) properly.
  • Keep server logic modular and clean.
  • For larger apps, use frameworks like Express.js for routing.

Conclusion

In this part of the Node.js Tutorial, we covered:

  • What is the HTTP module
  • Creating a basic web server
  • Handling requests and responses
  • Serving HTML and JSON data
  • A mini-project: Routing server

With this knowledge, you now know how Node.js can power real web servers.

👉 Up Next: Day 6 – Understanding NPM (Node Package Manager)

Leave a Reply

Your email address will not be published. Required fields are marked *