NodeJS

Simple HTTP Server in Node.js

📌 INTRODUCTION

Node.js allows developers to create web servers very easily using its built-in http module. This module helps us handle client requests and send responses from the server.

A simple HTTP server is one of the first and most important programs in Node.js because it introduces:

  • Server creation
  • Request handling
  • Response sending
  • Port listening

In this program, we will create a basic HTTP server using Node.js that listens for requests and responds with simple text or HTML.


📘 PROBLEM STATEMENT

👉 Develop a simple HTTP server in Node.js using the built-in http module. The server should listen for incoming requests and respond with basic text or HTML.


💡 CONCEPTS USED

  • Node.js http module
  • Server creation
  • Request and response objects
  • Port listening
  • Basic backend programming

🧠 LOGIC EXPLANATION

The server works in the following way:

  1. Import the http module
  2. Create a server using http.createServer()
  3. Accept client request using req
  4. Send response using res
  5. Listen on a port using server.listen()

💻 PROGRAM CODE

Create a file named server.js and write the following code:

const http = require("http");

const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello, World! This is a simple HTTP server in Node.js.");
});

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

▶️ HOW TO RUN THE PROGRAM

Open terminal in your project folder and run:

node server.js

Now open browser and visit:

http://localhost:3000

🖥️ OUTPUT

Terminal Output

Server is running at http://localhost:3000

Browser Output

Hello, World! This is a simple HTTP server in Node.js.

🔍 STEP-BY-STEP EXPLANATION

1. Import the http Module

const http = require("http");

This loads the built-in HTTP module of Node.js.


2. Create the Server

const server = http.createServer((req, res) => {
  • req represents the incoming request
  • res represents the response sent back to the client

3. Set Response Header

res.writeHead(200, { "Content-Type": "text/plain" });
  • 200 means request was successful
  • text/plain means plain text response will be sent

4. Send the Response

res.end("Hello, World! This is a simple HTTP server in Node.js.");

This sends the final response to the browser.


5. Start Listening on a Port

server.listen(3000, () => {

This tells the server to run on port 3000.


🎯 IMPORTANT METHODS USED

MethodPurpose
http.createServer()Creates an HTTP server
res.writeHead()Sets response status and headers
res.end()Ends the response and sends data
server.listen()Starts the server on a port

⚡ VERSION 2: RETURN HTML RESPONSE

You can also return HTML instead of plain text.

const http = require("http");

const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Welcome to Node.js Server</h1><p>This is an HTML response.</p>");
});

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

Browser Output

Welcome to Node.js Server
This is an HTML response.

⚡ VERSION 3: HANDLE DIFFERENT ROUTES

We can show different output for different URLs.

const http = require("http");

const server = http.createServer((req, res) => {
if (req.url === "/") {
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 Page</h1>");
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Page Not Found");
}
});

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

Example URLs

  • http://localhost:3000/ → Home Page
  • http://localhost:3000/about → About Page
  • any other URL → Page Not Found

⚡ VERSION 4: SEND JSON RESPONSE

A server can also send JSON data.

const http = require("http");

const server = http.createServer((req, res) => {
  const user = {
    name: "Nyra",
    course: "BBA"
  };

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

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

Browser Output

{"name":"Kavita","course":"MCA"}

🌟 WHY THIS PROGRAM IS IMPORTANT

This program is important because it teaches the basics of backend development:

  • How a server works
  • How browser requests are handled
  • How responses are sent
  • How different data formats can be returned

It is the foundation for:

  • Express.js applications
  • REST APIs
  • Full stack web development

📚 REAL-WORLD USE CASE

Simple HTTP servers are used in:

  • Testing backend logic
  • Serving HTML pages
  • Sending JSON APIs
  • Learning server-side development
  • Building web applications

❓ VIVA QUESTIONS (IMPORTANT)

Q1. What is the http module in Node.js?

👉 It is a built-in module used to create web servers and handle HTTP requests and responses.


Q2. What does http.createServer() do?

👉 It creates a new HTTP server.


Q3. What are req and res?

👉 req is the request object and res is the response object.


Q4. What is the use of res.writeHead()?

👉 It sets the response status code and headers.


Q5. What does res.end() do?

👉 It sends the response to the client and ends the request-response cycle.


Q6. What is the purpose of server.listen()?

👉 It starts the server on a specific port.


Q7. What is the difference between text/plain and text/html?

👉 text/plain sends plain text, while text/html sends HTML content.


Q8. Can Node.js return JSON data?

👉 Yes, by using application/json as content type and JSON.stringify().


🔗 RELATED POSTS

👉 MCA 168 Full Stack Development Lab Programs List
👉 Node.js File Upload Application – Program 21
👉 Node.js File Operations – Program 20


📌 CONCLUSION

A simple HTTP server in Node.js is the first step toward backend development. It helps you understand how servers handle requests and send responses.

👉 Practice the plain text version first, then try HTML, routes, and JSON responses. This will make your understanding much stronger.


Further Reading

JUnit Tutorial

How to Master Full Stack Development?

Spring Framework Practice Problems and Their Solutions

30 MCQs on JUnit

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

100+ MCQs On Java Architecture

Java Practice Exercise

programmingempire

Princites

You may also like...

Leave a Reply

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