Express.js Basics
Routing, middleware, request/response handling, and RESTful API design with Express.
Overview
Express.js is the most popular web framework for Node.js, providing a minimal and flexible approach to building web applications and APIs.
Key Concepts
- Routing — Define URL patterns and their handlers
- Middleware — Functions that execute during the request-response cycle
- Request Object —
req.params,req.query,req.body - Response Object —
res.json(),res.status(),res.send() - Router — Modular route handlers for organizing code
Code Examples
const express = require('express');
const app = express();
app.use(express.json());
app.get('/api/users', (req, res) => {
res.json([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);
});
app.post('/api/users', (req, res) => {
const { name } = req.body;
res.status(201).json({ id: 3, name });
});
app.listen(3000, () => console.log('API running on port 3000'));
Practice
Build a RESTful API with Express that supports CRUD operations for a resource.