Routing is how an Express application decides which code runs for a given URL and HTTP method. It is the backbone of every server you will build. In this lesson you will define routes for multiple paths, respond to different HTTP methods, and learn the matching rules that decide which handler wins.
A route is a combination of three things: an HTTP method, a path, and a handler function. The general shape is:
app.METHOD(PATH, HANDLER);METHOD is a lowercase HTTP verb such as get, post, put, patch, or delete. PATH is the URL pattern to match. HANDLER runs when both method and path match the incoming request.
A real site has many pages. Each gets its own route:
app.get('/', (req, res) => res.send('Home page'));
app.get('/about', (req, res) => res.send('About us'));
app.get('/contact', (req, res) => res.send('Contact page'));
app.get('/products', (req, res) => res.send('Product list'));Express checks routes in the order you registered them and uses the first match. That top-to-bottom rule is worth tattooing on your brain: it explains most 'why is my route not firing' bugs.
The same path can behave differently per method. This is the foundation of REST APIs, where methods map to CRUD operations:
app.get('/api/books', (req, res) => res.json({ action: 'read all books' }));
app.post('/api/books', (req, res) => res.status(201).json({ action: 'create a book' }));
app.put('/api/books', (req, res) => res.json({ action: 'replace a book' }));
app.delete('/api/books', (req, res) => res.json({ action: 'delete a book' }));GET reads data, POST creates, PUT/PATCH update, and DELETE removes. Browsers send GET when you type a URL; the other verbs usually come from forms, fetch calls, or tools like Postman and curl.
Sometimes you want one handler for every method on a path. app.all does that. And when several methods share a path, app.route removes repetition:
app.all('/health', (req, res) => res.send('OK'));
app.route('/api/movies')
.get((req, res) => res.json({ action: 'list movies' }))
.post((req, res) => res.status(201).json({ action: 'add movie' }));Paths are matched exactly by default, but Express supports patterns. In Express 5 you can use a named wildcard to match anything:
app.get('/files/*filePath', (req, res) => {
res.send('You asked for: ' + req.params.filePath);
});Keep patterns simple. If you find yourself writing clever regular expressions for routing, it is usually a sign the URL design needs rethinking.
You cannot trigger POST or DELETE from the browser address bar. Use curl from a second terminal:
curl -X POST http://localhost:3000/api/books
curl -X DELETE http://localhost:3000/api/booksGraphical clients like Postman, Insomnia, or the VS Code REST Client extension work too and are worth learning early.
Next lesson: Route Parameters and Query Strings, where routes become dynamic and can capture values straight from the URL.