• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Creating an HTTP Server with Node.js: A Comprehensive Guide

  • June 14, 2023
  • CODE OF GEEKS
  • 0
Creating an HTTP Server with Node.js: A Comprehensive Guide

Prerequisite: Understanding the Node.js HTTP Module

Creating an HTTP server is a crucial skill for web developers, and Node.js provides a seamless way to achieve this.

In this comprehensive guide, we will walk you through the process of creating an HTTP server using Node.js.

You’ll also learn how to handle different types of requests, implement routing, and parse important request data like headers, query parameters, and request bodies.

Introduction to http module

The HTTP module in Node.js is a built-in module that allows you to create and interact with HTTP servers and clients. It provides the necessary functionality to handle HTTP requests and responses, making it possible to build web servers, APIs, and interact with external HTTP-based services.

Step 1: Setting Up Your Project

To begin, set up your Node.js project by following these steps:

a. Create a new directory for your project: mkdir http-server-project
b. Navigate into the project directory: cd http-server-project
c. Initialize a new Node.js project:

npm init -y

d. Install the necessary dependencies, including the http module:

npm install http


Step 2: Creating the HTTP Server

Now that your project is set up, let’s create the HTTP server. Follow these steps:

const http = require('http');

const server = http.createServer((req, res) => {
  // Request handling logic goes here
});

const port = 3000;

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

Certainly! Let’s break down the code step by step:

1. const http = require(‘http’);: This line imports the built-in Node.js http module, which provides functionality for creating HTTP servers and handling HTTP requests and responses.

2. const server = http.createServer((req, res) => { … });: This line creates an HTTP server using the createServer method provided by the http module. The createServer method takes a callback function as an argument, which will be executed whenever a request is made to the server.

3. (req, res) => { … }: This is the callback function that handles the incoming requests and generates responses. The req parameter represents the incoming request object, and the res parameter represents the outgoing response object.

4. const port = 3000;: This line defines the port number on which the server will listen for incoming requests. In this case, the server will listen on port 3000.

5. server.listen(port, () => { … });: This line starts the server and makes it listen on the specified port. The listen method takes the port number and a callback function as arguments. The callback function is executed once the server starts listening, and it logs a message to the console indicating that the server is running.

6. console.log(Server is running on http://localhost:${port});: This line logs a message to the console, indicating that the server is running and specifying the URL where it can be accessed.

In summary, this code sets up a basic HTTP server using the http module in Node.js. The server listens for incoming requests on the specified port and executes the provided callback function to handle those requests.

To see the changes, run the command and open ‘localhost:3000’ on your browser.

node Node.js
Server up and running
Server up and running


Step 3: Handling Different Types of Requests and Implementing Routing

To handle different types of requests and implement routing, modify the server code as shown below:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.method === 'GET') {
    // Handle GET requests
    if (req.url === '/') {
      // Logic for the home route
    } else if (req.url === '/about') {
      // Logic for the about route
    } else {
      // Handle 404 - Not Found
      res.statusCode = 404;
      res.end();
    }
  } else if (req.method === 'POST') {
    // Handle POST requests
    // Implement your POST request handling logic here
  } else {
    // Handle other request methods
    res.statusCode = 405; // Method Not Allowed
    res.end();
  }
});

const port = 3000;

server.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});
#fact

GET Request is required when you want to fetch anything from server.
POST Request is required when you want to post/ send anything to server.

In summary, the provided code sets up an HTTP server using the http module in Node.js. It listens for incoming requests and handles them based on their method (GET, POST, etc.) and URL.

For GET requests, the code checks the URL and executes specific logic for the home route (/) and the about route (/about). If the URL doesn’t match any predefined routes, it sets the response status code to 404 (Not Found).

For POST requests, you can implement your specific logic to handle the requests inside the corresponding block.

For any other request methods, it sets the response status code to 405 (Method Not Allowed).

The server listens on a specified port, and once it starts running, it logs a message to the console indicating the server’s URL.

Hey! You have successfully learned how to create an HTTP server using Node.js. This guide has equipped you with the knowledge to handle different types of requests, implement routing, and parse essential request data like headers, query parameters, and request bodies. By applying these concepts, you can build powerful and scalable web applications.





Keywords for this tutorial:

Creating an HTTP server
HTTP server tutorial
Node.js HTTP server
Building a server in Node.js
Handling HTTP requests in Node.js
Routing in Node.js
Request parsing in Node.js
Node.js server tutorial
HTTP server implementation in Node.js
Server-side programming with Node.js
Basic HTTP server with Node.js
Node.js web development tutorial
Building a web server with Node.js
Node.js server setup
Handling different types of requests in Node.js
Node.js server creation
HTTP server setup in Node.js
Node.js server architecture
Request handling in Node.js
Node.js server routing techniques
Parsing request data in Node.js
Implementing RESTful APIs in Node.js
Node.js server best practices
Scaling Node.js servers
Performance optimization for Node.js servers
Securing Node.js servers
Node.js server deployment strategies
Debugging Node.js servers
Handling error responses in Node.js servers
Node.js server libraries and frameworks

Tags: Basic HTTP server with Node.jsBuilding a server in Node.jsBuilding a web server with Node.jsCreating an HTTP serverDebugging Node.js serversHandling different types of requests in Node.jsHandling error responses in Node.js serversHandling HTTP requests in Node.jsHTTP server implementation in Node.jsHTTP server setup in Node.jsHTTP server tutorialImplementing RESTful APIs in Node.jsNode.js HTTP serverNode.js server architectureNode.js server best practicesNode.js server creationNode.js server deployment strategiesNode.js server libraries and frameworksNode.js server routing techniquesNode.js server setupNode.js server tutorialNode.js web development tutorialParsing request data in Node.jsPerformance optimization for Node.js serversRequest handling in Node.jsRequest parsing in Node.jsRouting in Node.jsScaling Node.js serversSecuring Node.js serversServer-side programming with Node.js
  • Previous Reading Files in Node.js: A Comprehensive Guide to File Reading Operations
  • Next Understanding the Node.js HTTP Module: Building Efficient Web Servers

Leave a Reply Cancel reply

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

Advertise with us

More on Node.js

  • Introduction to Node.js
  • NPM in Node.js
  • Non-Blocking Nature of Node.js
  • First Application with Node.js
  • Node.JS Modules
  • HTTP Module Node.js
  • Reading File with Node.js
  • Writing File with Node.js
  • Creating File with Node.js
  • Updating File with Node.js
  • Deleting File with Node.js
  • Renaming File with Node.js
  • URL Module in Node.js
  • Event Programming with Node.js
  • async-await in Node.js
  • Buffer in Node.js
  • Sending Mails with Node.js
  • Connecting to MySQL(CRUD) in Node.js

More on Express.js

  • Introduction to Express.js
  • Creating First App with Express.js
  • Routes in Express.js
  • Middlewares in Express.js
  • Web App with Express & Pug
  • Web App with Express & EJS
  • Serving Static Files with Express.js
  • Handling Forms with Express.js
  • Handling File uploads in forms
  • Working with Cookies in Express.js
  • Session Handling with Express.js
  • REST API with Express.js
  • Validating Requests in Express.js
  • Fetch data from External API with axios
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.