Skip to main content

Command Palette

Search for a command to run...

Creating Routes and Handling Requests with Express

Updated
5 min read
Creating Routes and Handling Requests with Express

INTRODUCTION:

Imagine you’re building a food delivery app.

  • A user opens /menu → you show available dishes

  • A user submits an order → you process it

  • A user checks /status → you return order status

Without a proper routing system, your server would be messy and hard to manage.

This is exactly where Express.js shines it helps you organize how your server responds to different requests cleanly and efficiently.

In this blog, we’ll dive into how Express.js transforms the complex, manual overhead of raw Node.js into a streamlined, intuitive system for routing and request handling.

What is Express.js?

Express.js is a fast, unopinionated, and minimalist web framework for Node.js. It acts as an abstraction layer over the native http module, providing specialized tools for handling HTTP requests, responses, and middleware.

  • Framework → Pre-built structure to simplify development

  • Middleware → Functions that run between request and response

  • Routing → Mapping URLs to specific logic

Express.js is a minimal and flexible Node.js web framework used to build web servers and APIs.

Why Express Simplifies Development

Raw Node.js requires manual parsing of request streams and complex conditional logic to manage different URLs. Express automates these tasks through high-level methods.

Raw Node.js (HTTP module):

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);

Express Version:

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);

Feature

Raw Node.js (http)

Express.js

Routing

Manual parsing of req.url.

Intuitive .get(), .post() methods.

Boilerplate

High; requires manual stream handling.

Low; streamlined with helper methods.

Middleware

Difficult to implement.

Native support for modular logic.

Response

res.end() (requires headers).

res.send() or res.json() (auto-headers).

The Express Flow: Visualized

Before we code, understand how data moves through the system.

Request → Route Handler → Response Flow:

[ Client ]  ---- (HTTP Request) ---->  [ Express Server ]
                                               |
                                        [ Route Matching ]
                                     (Is it GET /? Is it POST /?)
                                               |
                                        [ Handler Function ]
                                     (Logic / Database / Auth)
                                               |
  [ Client ]  <--- (HTTP Response) <-----------+

Routing Structure

Express organizes code by matching incoming requests to specific handler functions based on the URL path and HTTP method.

Express Routing Visualization

[ Client ] 
    |
    |--- (GET /home) ----> [ Route: /home ] ----> (Function: Send HTML)
    |
    |--- (POST /login) ---> [ Route: /login ] ---> (Function: Verify User)
    |
    |--- (GET /api) ------> [ Route: /api ] ----> (Function: Send JSON)

Creating the First Express Server

A basic server requires importing the module, initializing the application, and binding it to a network port.

const express = require("express"); // Import
const app = express();             // Create app

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

What’s happening:

  • express() → creates server instance

  • app.listen() → starts server

Handling GET requests

A GET request is used to retrieve data from a server. In Express, we define a "route" using app.get().

GET request = Fetch data from server

// Syntax: app.get(path, callback)
app.get('/', (req, res) => {
    res.send('Welcome to the Homepage!');
});

app.get('/api/user', (req, res) => {
    res.json({ name: 'Alex', role: 'Developer' });
});
  • req → Request object (data from client)

  • res → Response object (data sent back)

Handling POST requests

A POST request is used to send data to the server (like submitting a form). To read the incoming data (the "body"), we use a middleware to parse JSON.

POST request = Send data to server

// Middleware to help Express understand JSON data
app.use(express.json()); 

app.post('/contact', (req, res) => {
    const userName = req.body.name;
    
    // Sending a structured response
    res.status(201).send(`Received! Thank you, ${userName}.`);
});
  • express.json() → parses incoming JSON data

  • req.body → contains client data

Request-Response Flow

The interaction between the client and the server follows a strict execution chain.

  CLIENT              EXPRESS SERVER
    |                       |
    | --(1) HTTP Request--> |
    |                       |-- (2) Match Route (e.g., /api)
    |                       |-- (3) Execute Handler Logic
    | <--(4) HTTP Response- |
    |                       |

Key Takeaways

  • Middleware First: Always use app.use(express.json()) if you plan to handle POST data.

  • Method Matching: Express matches the HTTP Verb (GET, POST, PUT, DELETE) and the URL Path to trigger the right function.

  • The "res" Advantage: Express automatically sets the Content-Type for you when you use res.send() or res.json().

  • Efficiency: Use Express to keep your code DRY (Don't Repeat Yourself) compared to the manual logic required in raw Node.js.

In closing

I hope that you’ve found this blog on “Creating Routes and Handling Requests with Express” helpful...!

That's all for today! 😁 You reached the end of the article 😍.

Want more..?

I write articles on princekumar-engineer.hashnode.dev, and also post development-related content on the following platforms:

Node.js

Part 9 of 15

A complete beginner-to-advanced guide to learning Node.js and Express.js, covering core concepts, asynchronous programming, REST APIs, middleware, file handling, and authentication techniques.

Up next

What is Middleware in Express and How It Works

INTRODUCTION: Imagine you enter an airport.Before boarding your flight, you pass through multiple checkpoints: Security check 🛂 Identity verification 🪪 Baggage scanning 🎒 Only after clearing a