3.3 Creating a Basic HTTP Server with Node.js

Table of Contents

Hey Codders! 👋
It’s me, Vikas Sankhla from Web Codder. Today, we’re building something cool and real—our very own web server using Node.js! 🤩

No worries if this sounds hard. I’ll guide you step by step with easy words, fun code, and visuals. 🛠️


🚀 What Is a Server Anyway?

A server is like a shop 🏪.

  • You (the user) come in and ask for something (like a toy 🚂).
  • The shop gives you what you asked for (the toy).

A web server does the same!
You ask for a webpage, and it gives you the page. 📄


🛠️ Setting Up a Basic HTTP Server

In Node.js, we use the http module to create a server.

Step 1️⃣: Create a server.js File

Open your code editor and make a new file called server.js. ✍️


Step 2️⃣: Add This Code

jsCopyEditconst http = require('http');

const server = http.createServer((req, res) => {
  res.write('Hello from Web Codder! 🚀');
  res.end();
});

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

6087748Dfc5Ec52Acee6960E 1589348637 Vscode Collaboration
3.3 Creating A Basic Http Server With Node.js 3


✅ What’s Happening?

  • http.createServer() → We create the server.
  • (req, res) => {} → We set up what the server does when someone visits.
  • server.listen(3000) → The server listens on port 3000 (like a door 🚪 number).

🔗 Test Your Server

1️⃣ Open your terminal.
2️⃣ Run:

bashCopyEditnode server.js

3️⃣ Go to your browser and type:
👉 http://localhost:3000

🎉 You’ll see: “Hello from Web Codder! 🚀”


📦 Handling Routes (GET, POST, etc.)

What if we want to handle different URLs?

Example:

  • / → Home page 🏠
  • /about → About page ℹ️

📝 Updated Code:

jsCopyEditconst http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.write('Welcome to the Home Page! 🏠');
  } else if (req.url === '/about') {
    res.write('This is the About Page. ℹ️');
  } else {
    res.write('404 Not Found 🚫');
  }
  res.end();
});

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

📮 Handling Different HTTP Methods

Let’s say someone sends data to your server. 🚚
We handle that with methods like GET, POST, PUT, DELETE.

Example: Only handle POST requests to /submit.

✍️ Code:

jsCopyEditconst http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/submit' && req.method === 'POST') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      res.write('Data received: ' + body);
      res.end();
    });
  } else {
    res.write('Welcome! 😊');
    res.end();
  }
});

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

1718998421506
3.3 Creating A Basic Http Server With Node.js 4


📬 Request & Response Objects

Let’s look closer at req and res:

ObjectWhat It Does
reqTells you what the user asked for (URL, method, data)
resLets you send something back (HTML, text, data)

✅ Quick Recap Table

ConceptExample
Create serverhttp.createServer()
Handle routesif (req.url === '/about') { ... }
GET requestBrowser asking for a page
POST requestForm sending data to the server
req & res objectsreq.method, req.url, res.write(), res.end()

🎯 Conclusion

And that’s it, Codders! 🎉 You now know how to:

  • ✅ Build a basic HTTP server
  • ✅ Handle routes
  • ✅ Work with GET & POST requests
  • ✅ Understand req & res objects

Isn’t that awesome? 🌟


👉 Keep Learning with Us:

Share the Post:
Picture of Web Codder

Web Codder

Vikas Sankhla is a seasoned Full Stack Developer with over 7 years of experience in web development. He is the founder of Web Codder, a platform dedicated to providing comprehensive web development tutorials and resources. Vikas specializes in the MERN stack (MongoDB, Express.js, React.js, Node.js) and has been instrumental in mentoring aspiring developers through his online courses and content. His commitment to simplifying complex web technologies has made him a respected figure in the developer community.

Related Posts