Topic 39 of 55
Express Basic Route Mappings
Overview
Routing refers to how an application responds to a client request for a specific endpoint (a URL/path and a specific HTTP method like GET or POST). Express makes this highly intuitive.
Syntax
javascript
const app = require('express')();
// app.METHOD(PATH, HANDLER_FUNCTION)
app.get('/', (req, res) => {
res.send('Homepage (GET)');
});
app.post('/submit', (req, res) => {
res.send('Form submitted (POST)');
});
app.put('/update', (req, res) => {
res.send('Data fully updated (PUT)');
});
app.delete('/remove', (req, res) => {
res.send('Data deleted (DELETE)');
});
// Matches ALL HTTP methods for a specific path
app.all('/universal', (req, res) => {
res.send('Matches GET, POST, PUT, DELETE, etc.');
});Common Pitfalls
- Order matters! Express reads routes from top to bottom. If you place a catch-all wildcard route at the top of your file, none of the routes below it will ever execute.
- A single request can only receive one response. If you call `res.send()` twice in the same route handler, Express will throw a 'Cannot set headers after they are sent to the client' error.
Real-World Example
Using wildcards and regex in Express routes:
example
javascript
// Exact match
app.get('/about', (req, res) => res.send('About Page'));
// Wildcard match (matches anything starting with /api/)
app.get('/api/*', (req, res) => {
res.send('API Endpoint hit');
});
// Regex match (matches /fly or /butterfly)
app.get(/.*fly$/, (req, res) => {
res.send('Matches anything ending in "fly"');
});
// The 404 Catch-All (Must be placed at the very bottom of your routes!)
app.use((req, res) => {
res.status(404).send("404: Page not found");
});