Express Framework
Building with Express
Build web servers and REST APIs with Express.js — the most popular Node.js framework.
What is Express?
Express is a minimal, flexible Node.js web framework. It provides routing, middleware support, and request/response handling — making it the go-to choice for building APIs.
Core Concepts
- Routes: URL patterns + HTTP methods that map to handler functions
- Middleware: Functions that run before your route handlers. Used for logging, authentication, parsing request bodies, etc.
- Request/Response: Express enhances Node's req/res objects with helpful methods
REST API Design
A REST API uses HTTP methods semantically:
GET— read dataPOST— create dataPUT/PATCH— update dataDELETE— remove data
Example
nodejs
const express = require('express');
const app = express();
// Middleware
app.use(express.json()); // Parse JSON bodies
app.use(express.urlencoded({ extended: true }));
// Simple logging middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Pass to next middleware/route
});
// In-memory data store
let users = [
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' },
];
// GET all users
app.get('/api/users', (req, res) => {
res.json(users);
});
// GET single user
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
});
// POST create user
app.post('/api/users', (req, res) => {
const { name, email } = req.body;
const user = { id: Date.now(), name, email };
users.push(user);
res.status(201).json(user);
});
// DELETE user
app.delete('/api/users/:id', (req, res) => {
const id = parseInt(req.params.id);
users = users.filter(u => u.id !== id);
res.status(204).send();
});
app.listen(3000, () => console.log('Server on port 3000'));Try it yourself — NODEJS