Express.js — Basic Routes & HTTP Methods
Welcome to Express.js — Basic Routes & HTTP Methods in our Express.js Complete Masterclass! Define HTTP verb endpoints (GET, POST, PUT, DELETE) and handle 404 unknown routes.
HTTP routing determines how an Express application responds to client requests at specific URIs using methods like GET, POST, PUT, PATCH, and DELETE. A catch-all 404 middleware registered at the end of the stack captures all unmatched route requests.
- Master the underlying Node.js event loop mechanics for Basic Routes & HTTP Methods.
- Implement non-blocking, asynchronous execution pipelines in compliance with production API standards.
- Enforce strict OWASP Top 10 API security guidelines and performance optimizations.
| HTTP Verb | Primary Purpose | Idempotent | Request Body |
|---|---|---|---|
| GET | Retrieve resources without side effects | Yes | No |
| POST | Create a new resource record | No | Yes |
| PUT | Replace an existing resource completely | Yes | Yes |
| PATCH | Apply partial updates to a resource | No | Yes |
| DELETE | Remove a specific resource record | Yes | Optional |
import express from 'express';
const app = express();
app.use(express.json());
app.get('/courses', (req, res) => res.json([{ id: 1, title: 'Express' }]));
app.post('/courses', (req, res) => res.status(201).json({ id: 2, ...req.body }));
app.put('/courses/:id', (req, res) => res.json({ id: req.params.id, updated: true }));
app.delete('/courses/:id', (req, res) => res.json({ id: req.params.id, deleted: true }));
// 404 Catch-All Handler
app.use((req, res) => {
res.status(404).json({ error: 'Resource Not Found' });
});
// RESTful Compliance Controller
import express from 'express';
const app = express();
app.patch('/api/v1/users/:id', (req, res) => {
res.status(200).json({ message: 'User partial fields updated successfully' });
});
app.listen(3000);
- Placing dynamic wildcard routes above static routes, causing static endpoints to be swallowed.
- Using GET requests for state-mutating actions like database deletion.
❓ Question: Difference between PUT and PATCH?
Answer: PUT requires submitting the complete resource object to replace existing data. PATCH accepts partial field updates without modifying unspecified attributes.
❓ Question: Why is route order crucial in Express?
Answer: Express evaluates routes sequentially from top to bottom. If a broad wildcard route is placed at the top, subsequent routes will never be reached.
Create CRUD endpoints for a `/books` resource (GET, POST, PUT, DELETE) and append a 404 fallback handler returning JSON.