WikiGalaxy

Personalize

Creating Web Servers with HTTP Module

Introduction to HTTP Module

Node.js provides a built-in module called HTTP which allows developers to create web servers and handle HTTP requests and responses. This module is essential for building server-side applications in Node.js.

Creating a Basic HTTP Server

The HTTP module can be used to create a simple server that listens for requests on a specified port. This is the foundation for any web application built using Node.js.

Handling Requests and Responses

Once a server is created, it can handle incoming requests and send appropriate responses. This involves parsing request data and sending back data in the form of HTML, JSON, etc.

Server Configuration and Routing

Configuring the server to handle different routes and methods (GET, POST, etc.) is crucial for building RESTful services and APIs.

Error Handling

Proper error handling ensures that the server can gracefully handle unexpected situations without crashing.

Example: Basic HTTP Server


const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;

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

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

Explanation

This code sets up a basic HTTP server that listens on localhost (127.0.0.1) at port 3000. When a request is made, it responds with "Hello, World!". This is the simplest form of a Node.js server.

Example: Handling Different Routes


const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;

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

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

Explanation

This example demonstrates how to handle different routes using the HTTP module. The server responds with different messages based on the URL path. If the path doesn't match any predefined route, it returns a 404 error.

Example: Serving JSON Data


const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  const data = { message: 'Hello, JSON!' };
  res.end(JSON.stringify(data));
});

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

Explanation

This code snippet shows how to serve JSON data using the HTTP module in Node.js. The server sends a JSON object as a response, which can be useful for APIs returning structured data.

Example: Handling POST Requests


const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  if (req.method === 'POST') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain');
      res.end(`Received data: ${body}\n`);
    });
  } else {
    res.statusCode = 405;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Method Not Allowed\n');
  }
});

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

Explanation

This example illustrates how to handle POST requests in a Node.js server. The server listens for data being sent in the request body and outputs it once the entire body has been received.

Example: Error Handling


const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  try {
    if (req.url === '/error') {
      throw new Error('Forced error');
    }
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('No errors here!\n');
  } catch (err) {
    res.statusCode = 500;
    res.setHeader('Content-Type', 'text/plain');
    res.end(`Server Error: ${err.message}\n`);
  }
});

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

Explanation

This code demonstrates basic error handling in a Node.js HTTP server. It includes a route that deliberately throws an error, showing how to catch and respond to exceptions gracefully.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025