Why Express?
Node.js gives you low-level tools to work with HTTP.
Express sits on top of Node and makes it easier to:
- create servers
- define routes
- handle requests and responses
- organize backend code
Express helps you focus on what your API does, not boilerplate.
Creating Your First Express Server
Install Express:
npm install express
Create a basic server:
import express from "express";
const app = express();
app.get("/", (req, res) => {
res.json({ message: "Hello Express" });
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Visit http://localhost:3000 in your browser.
Request & Response (Mental Model)
Every request follows this flow:
Client → Request → Server → Response → Client
The animation above shows how a request enters your server, hits a route, and returns a response.
Routing Basics
Routes are defined by:
- HTTP method
- URL path
app.get("/users", (req, res) => {
res.json([]);
});
app.post("/users", (req, res) => {
res.json({ created: true });
});
Each route handles one responsibility.
Route Parameters
app.get("/users/:id", (req, res) => {
const userId = req.params.id;
res.json({ userId });
});
Dynamic routes let you work with specific resources.
Interactive Exercise: Route Matching
Try this:
- Define different routes
- Change the URL
- Observe which route matches
Quick Exercise (Offline)
- Create
/usersand/productsroutes - Add one route with a URL parameter
- Return JSON from every route