Creating Routes and Handling Requests with Express
Express.js is often described as the "de facto" standard web framework for Node.js. If Node.js is the engine, Express is the dashboard and steering wheel that makes driving the vehicle actually manageable.
What is Express.js?
Express is a minimal and flexible web development framework. It provides a robust set of features for web and mobile applications without obscuring the Node.js features you already know. It sits on top of Node's built in http module, acting as a layer of "syntactic sugar" that handles the heavy lifting of server management.
Why Express Simplifies Node.js Development
Building a server using only the native Node.js http module is powerful but incredibly verbose. To understand why Express is the industry standard, let's compare how you handle a basic route in both.
The Comparison: Raw Node vs. Express
| Feature | Raw Node.js http |
Express.js |
|---|---|---|
| Routing | Mannual if/else logic based on req.url. |
Declarative syntax: app.get("/path", ....). |
| Request Parsing | Requires manual data buffering for POST bodies. | Built-in middleware (e.g., express.json()). |
| Boilerplate | High; you must set every header manually. | Low; many sensible defaults are pre-configured. |
The Conceptual Shift: In raw Node, you are inspecting a stream of data. In Express, you are defining a series of "actions" (routes) that the server should take when a specific URL is hit.
Creating Your First Express Server
To get started, you need to initialize your project and install the package:
npm init -y
npm install express
Here is the "Hello World" of Express:
const express = require("express");
const app = express();
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on https://localhost:${PORT}`);
});
Handling GET Requests
GET requests are used to retrieve data from the server. In Express, you define a route using app.get(). This method takes two arguments: the path and a callback function (the handler).
// Handling a GET request to the homepage
app.get("/", (req, res) => {
res.send("Welcome to the Home Page!");
});
// Handling a GET request with a JSON response
app.get("/api/user", (req, res) => {
res.json({
id: 1,
name: "John",
role: "Developer"
});
});
Handling POST Requests
POST requests are used to send data to the server (e.g., submitting a form or creating a new user). To access the data sent in the request body, you must use Express's built-in middleware to parse JSON.
// Middleware to parse JSON bodies
app.use(express.json());
app.post('/api/user', (req, res) => {
const newUser = req.body;
console.log('Received data:', newUser);
res.send(201).send('User created sucessfully!')
});
Sending Responses
Express enhances the res (response) object with several methods that make it easier to communicate back to the client:
res.send(): Sends a basic string or HTML response. It automatically sets theContent-Type.res.json(): Sends a JSON response. This is the standard for modern APIs.res.status():Sets the HTTP status code (e.g.,404for Not Found,200for OK).res.redirect(): Forwards the user to a different URL.
Minimal Example: The Complete Flow
const express = require('express');
const app = express();
app.use(express.json());
// 1. GET: Fetching a message
app.get('/hello', (req, res) => {
res.status(200).json({ message: "Hello from Express!" });
});
// 2. POST: Receiving data
app.post('/echo', (req, res) => {
res.json({
received: req.body,
status: "Success"
});
});
app.listen(3000);
By using Express, you transform a complex web of if statements into a clean, readable, and scalable architecture. It allows you to focus on the logic of your application rather than the protocol of web.


