โš™๏ธ Node.js Core Concepts & Features
Estimated reading: 4 minutes 280 views

Node.js โ€“ Web Module โ€“ Create HTTP Servers Using Built-In http and https Modules


Introduction โ€“ What Is the Web Module in Node.js?

Node.js comes with built-in support for web development through the http and https modules. These core modules let you create full-featured web servers, handle routing, serve HTML content, and respond to HTTP requestsโ€”all without needing third-party frameworks like Express.

In this guide, youโ€™ll learn:

  • How to create HTTP and HTTPS servers using Node.js
  • Handle GET, POST, and other request methods
  • Serve files and send responses
  • Compare http with Express.js (optional upgrade path)

The http Module โ€“ Create Basic Web Server

The http module lets you build a web server that listens for requests and sends responses.

Example โ€“ Simple HTTP Server

const http = require('http');

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

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

Output (Browser/Terminal):

Hello from Node.js Web Server!

Handling Different Routes

const http = require('http');

http.createServer((req, res) => {
  if (req.url === '/') {
    res.end('Home Page');
  } else if (req.url === '/about') {
    res.end('About Page');
  } else {
    res.writeHead(404);
    res.end('404 Not Found');
  }
}).listen(3000);

Visiting:

  • / โ†’ “Home Page”
  • /about โ†’ “About Page”
  • /xyz โ†’ “404 Not Found”

๐Ÿ“ฉ Handling POST Requests (With Body)

const http = require('http');

http.createServer((req, res) => {
  if (req.method === 'POST') {
    let body = '';
    req.on('data', chunk => (body += chunk));
    req.on('end', () => {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end(`Received POST data: ${body}`);
    });
  } else {
    res.end('Send a POST request');
  }
}).listen(3000);

POST with data: "name=NodeJS"
Response:

Received POST data: name=NodeJS

https Module โ€“ Create Secure Server (SSL)

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

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Secure Server');
}).listen(443);

Requires SSL certificate files: key.pem and cert.pem.


Serving Static HTML File

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

http.createServer((req, res) => {
  fs.readFile('index.html', (err, data) => {
    if (err) {
      res.writeHead(404);
      res.end('File not found');
    } else {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(data);
    }
  });
}).listen(3000);

Visiting localhost:3000 loads index.html.


http Module โ€“ Key Methods & Properties

Method / PropertyDescription
createServer()Creates a new web server instance
req.methodHTTP method (GET, POST, etc.)
req.urlURL path of the incoming request
res.writeHead()Set status code and headers
res.end()Send the response and close connection

http vs Express โ€“ Quick Comparison

Featurehttp (Core Module)Express.js (Framework)
RoutingManual if/else blocksBuilt-in routing system
MiddlewareNot availableFull middleware support
File ServingManual using fsexpress.static() support
PerformanceFaster (bare metal)Slight overhead with features
Use CaseSmall tools, custom stacksFull-featured web APIs

Summary โ€“ Recap & Next Steps

The Node.js Web Module (http and https) is a powerful low-level API for creating web servers. While frameworks like Express simplify things, understanding the core http module gives you full control and insight into how requests are handled.

Key Takeaways:

  • Use http.createServer() for building web servers
  • Handle GET/POST routes using req.method and req.url
  • Use https for secure communication
  • Serve HTML, handle form data, and respond dynamically

Real-world relevance:
Used in custom microservices, static file servers, CLI tools, and when building your own lightweight backend stack.


FAQs โ€“ Node.js Web Module (http, https)


What port should I use for HTTP and HTTPS?
Use port 80 for HTTP and 443 for HTTPS (default web ports). You can use custom ports for development like 3000 or 8080.


Can I serve JSON using http module?
Yes. Just set Content-Type to application/json:

res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ name: "Node.js" }));

How do I redirect a user in http?
Use status code 302 or 301:

res.writeHead(302, { Location: '/new-url' });
res.end();

Is it necessary to use Express for web apps?
No. You can build complete applications using only http, but Express simplifies routing, middleware, and error handling.


How to stop a running server in Node.js?
You can call:

server.close();

Or press CTRL + C in the terminal.


Share Now :
Share

๐ŸŒ Node.js โ€“ Web Module

Or Copy Link

CONTENTS
Scroll to Top