Day 12: Setting up an Express Server + Basic Routes

Payal PorwalPayal Porwal
4 min read

🧠 What You Will Learn Today

  • What is a server?

  • Why do we use Express?

  • How to create an Express server?

  • What are routes in Express?

  • Real-life example: Build a mini product API

  • Step-by-step code explanation

  • FAQs


πŸ–₯️ What Is a Server?

A server is just a computer (or code) that listens for requests and responds with data.

In web development:

  • Client = Browser / Frontend (React, etc.)

  • Server = Backend (Node.js + Express)


πŸ’‘ Why Use Express for Server?

Without Express, you have to write a lot of code to:

  • Handle routes

  • Parse data

  • Send responses

But with Express.js, you can write clean, fast code for:
βœ… APIs
βœ… Middlewares
βœ… Error handling
βœ… Route handling


πŸ› οΈ Let's Build: Product API (Basic Express Server)

We’ll create a simple API with 3 routes:

  • / β†’ Home route

  • /products β†’ All products

  • /about β†’ About page


πŸ“ Project Structure

express-server/
└── index.js

βœ… Step 1: Create a New Folder

mkdir express-server
cd express-server

βœ… Step 2: Initialize Project & Install Express

npm init -y
npm install express

βœ… Step 3: Create index.js File

echo. > index.js

🧾 Full Code with Explanation

// index.js

const express = require("express");       // Import express
const app = express();                    // Create app instance
const port = 5000;                        // Port where server will run

// Middleware to handle JSON (important for POST, PUT later)
app.use(express.json());

// Home route
app.get("/", (req, res) => {
  res.send("Welcome to our Home Page!");
});

// Products route
app.get("/products", (req, res) => {
  const products = [
    { id: 1, name: "Mobile", price: 10000 },
    { id: 2, name: "Laptop", price: 45000 },
  ];
  res.json(products);
});

// About route
app.get("/about", (req, res) => {
  res.send("This is a demo Express API project.");
});

// Start the server
app.listen(port, () => {
  console.log(`πŸš€ Server is running at http://localhost:${port}`);
});

▢️ How to Run

  1. Open terminal

  2. Navigate to your folder

  3. Run:

node index.js

Now open your browser or Postman and visit:


🧠 What You Learned

ConceptWhat it means
express()Creates the Express app
app.get()Handles GET requests
res.send()Sends simple text/html as response
res.json()Sends structured data (like objects/arrays)
app.listen()Starts the server on the given port
express.json()Middleware to parse JSON data (needed later)

πŸ’‘ Real-Life Use Case

Imagine you’re building the backend for a shopping website. These routes help you:

  • Show homepage β†’ /

  • List all products β†’ /products

  • Company details β†’ /about

Later, you’ll add more routes like:

  • /products/:id

  • /add-product

  • /delete-product


πŸ” Code Flow Summary

Client (browser) β†’ Server (Express) β†’ Route matched β†’ Response sent

❓ FAQs – Beginner-Friendly Questions


1. What is the purpose of express.json()?

It allows Express to understand JSON data from client (used in POST, PUT routes).


2. Can we run this server on any port?

Yes! But make sure that port is not being used by another app (like React dev server).


3. What happens if a route is not defined?

You’ll get a Cannot GET /something error.
To handle this, we can add a 404 route later like:

app.use((req, res) => {
  res.status(404).send("Route not found");
});

4. Is Express still maintained and modern?

βœ… Yes. Express is stable, maintained, and widely used in production (including MERN stack apps).


🏁 Practice Task for Students

  1. Add one more route: /contact β†’ return contact email

  2. Add a new route: /products/:id β†’ return product by ID (static for now)

  3. Use Postman to test /products route


βœ… Final Summary

FeatureStatus
Express serverβœ… Created
Routes addedβœ… /, /products, /about
JSON responseβœ… Used res.json()
Middleware usedβœ… express.json()
Browser testingβœ… Works on http://localhost:5000

πŸ”” Stay Connected

If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Node JS notes, tutorials, and project ideas β€” πŸ“© Subscribe to our newsletter by entering your email below.

And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment, πŸŽ₯ Don’t forget to subscribe to my YouTube channel – Knowledge Factory 22 – for regular content on tech concepts, career tips, and coding insights!

Stay curious. Keep building. πŸš€

0
Subscribe to my newsletter

Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Porwal
Payal Porwal

Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: πŸš€ In-depth explorations of emerging technologies πŸ’‘ Practical tutorials and how-to guides πŸ”§Insights on software development best practices πŸš€Reviews of the latest tools and frameworks πŸ’‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟