Skip to main content

Command Palette

Search for a command to run...

Creating Routes and Handling Requests with Express

Updated
7 min readView as Markdown

Modern web applications constantly receive requests from users. Whether someone opens a webpage, submits a login form, or fetches data from an API, the server must know how to respond correctly.

Node.js provides the ability to create servers using its built-in http module, but writing everything manually quickly becomes repetitive and difficult to manage. This is where Express.js becomes extremely useful.

Express simplifies server development by making routing, request handling, and response management cleaner and easier to understand.

In this blog, you’ll learn:

  • What Express.js is

  • Why developers prefer Express

  • How to create your first Express server

  • How routing works

  • Handling GET and POST requests

  • Sending responses back to users


What Is Express.js?

Express.js is a lightweight web framework built on top of Node.js.

It provides tools and features that make backend development much easier compared to using raw Node.js alone.

With Express, developers can:

  • Create servers faster

  • Handle routes easily

  • Process requests cleanly

  • Build APIs efficiently

  • Organize backend code better

Express is one of the most widely used frameworks in the Node.js ecosystem because it reduces boilerplate code and improves readability.


Why Express Simplifies Node.js Development

To understand Express properly, compare it with a raw Node.js HTTP server.

Creating a Server Using Raw Node.js

const http = require("http");

const server = http.createServer((req, res) => {
    if (req.url === "/") {
        res.end("Home Page");
    } else if (req.url === "/about") {
        res.end("About Page");
    }
});

server.listen(3000);

This works, but problems appear quickly:

  • Routing becomes messy

  • Request handling becomes repetitive

  • Code becomes harder to maintain

  • Large applications become difficult to organize

Now look at the same thing using Express.


Express Server Example

const express = require("express");

const app = express();

app.get("/", (req, res) => {
    res.send("Home Page");
});

app.get("/about", (req, res) => {
    res.send("About Page");
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

This version is:

  • Cleaner

  • More readable

  • Easier to scale

  • Easier to organize

Express removes unnecessary complexity so developers can focus on application logic instead of low-level server handling.


Installing Express

Before creating an Express application, initialize a Node.js project.

Step 1: Create Project Folder

mkdir express-app
cd express-app

Step 2: Initialize Node Project

npm init -y

This creates a package.json file.


Step 3: Install Express

npm install express

Express is now added to your project.


Creating Your First Express Server

Create a file named server.js.

const express = require("express");

const app = express();

app.listen(3000, () => {
    console.log("Server is running on port 3000");
});

Run the server:

node server.js

Your server is now active on:

http://localhost:3000

Understanding Routing in Express

Routing means deciding how the server should respond to different URLs and request types.

For example:

URL Purpose
/ Homepage
/about About page
/contact Contact page

Express makes routing extremely simple.

Basic syntax:

app.METHOD(PATH, HANDLER)

Example:

app.get("/", (req, res) => {
    res.send("Welcome");
});

Here:

  • app.get() handles GET requests

  • / is the route path

  • Callback function runs when request arrives


Handling GET Requests

GET requests are used to fetch or retrieve data.

Examples:

  • Opening a webpage

  • Fetching user information

  • Loading products from a database

Example of GET Request

const express = require("express");

const app = express();

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

app.get("/about", (req, res) => {
    res.send("This is About Page");
});

app.listen(3000);

When users visit:

  • / → Home Page response

  • /about → About Page response


Understanding Request and Response Objects

Every route handler receives two important objects:

(req, res)

req Object

Represents the incoming request.

Contains information like:

  • URL

  • Headers

  • Query parameters

  • Request body


res Object

Used to send a response back to the client.

Examples:

res.send("Hello");
res.json({ name: "Aslam" });
res.status(404).send("Not Found");

Sending Responses in Express

Express provides multiple ways to send responses.


Sending Plain Text

res.send("Hello World");

Sending JSON Data

res.json({
    name: "Aslam",
    role: "Developer"
});

JSON responses are commonly used in APIs.


Sending Status Codes

res.status(404).send("Page Not Found");

Status codes help clients understand what happened.

Common examples:

Status Code Meaning
200 Success
404 Not Found
500 Server Error

Handling POST Requests

POST requests are used to send data to the server.

Examples:

  • Login forms

  • Registration forms

  • Uploading data

  • Creating new records

Before handling POST data, Express needs middleware to read JSON input.


Using Express Middleware

Add this line:

app.use(express.json());

This allows Express to understand JSON data from requests.


Example of POST Request

const express = require("express");

const app = express();

app.use(express.json());

app.post("/user", (req, res) => {

    const userData = req.body;

    res.send(`User ${userData.name} created successfully`);
});

app.listen(3000);

If client sends:

{
    "name": "Aslam"
}

The server responds:

User Aslam created successfully

Difference Between GET and POST Requests

Feature GET POST
Purpose Fetch data Send data
Data Location URL Request body
Visibility Visible in URL Hidden from URL
Common Use Reading data Creating data

Real-World Routing Example

Here is a small example combining multiple routes.

const express = require("express");

const app = express();

app.use(express.json());

app.get("/", (req, res) => {
    res.send("Welcome to API");
});

app.get("/products", (req, res) => {
    res.json([
        { id: 1, name: "Laptop" },
        { id: 2, name: "Phone" }
    ]);
});

app.post("/products", (req, res) => {

    const newProduct = req.body;

    res.json({
        message: "Product added",
        product: newProduct
    });
});

app.listen(3000, () => {
    console.log("Server running");
});

This structure is much cleaner than manually managing everything with raw Node.js.


Express became popular because it solves practical backend problems efficiently.

Key advantages:

  • Minimal syntax

  • Fast development

  • Clean routing system

  • Middleware support

  • Large ecosystem

  • Easy API creation

  • Better project organization

It allows developers to build scalable applications without writing excessive boilerplate code.


Common Beginner Mistakes

1. Forgetting Middleware

Without:

app.use(express.json());

req.body will often be undefined.


2. Wrong HTTP Method

Using GET instead of POST can break API behavior.

Always choose the correct request type.


3. Missing Response

Every route should send a response.

Wrong:

app.get("/", (req, res) => {

});

Correct:

app.get("/", (req, res) => {
    res.send("Hello");
});

Without a response, requests may hang indefinitely.


Conclusion

Express.js makes backend development in Node.js significantly easier by simplifying routing and request handling.

Instead of manually managing low-level HTTP logic, Express provides a clean and readable structure for:

  • Creating servers

  • Defining routes

  • Handling requests

  • Sending responses

  • Building APIs

Understanding routing and request handling is one of the most important foundations of backend development. Once you become comfortable with Express basics, you can move toward:

  • REST APIs

  • Middleware

  • Authentication

  • Database integration

  • Full-stack applications

Express is simple enough for beginners while still powerful enough for large production systems.

3 views