Routing helps your web app decide what to do when someone visits different web addresses. It connects the address they type to the right response or page.
0
0
Why routing matters in Express
Introduction
When you want to show different pages or data for different web addresses.
When you need to handle user actions like submitting a form or clicking a link.
When building APIs that respond differently based on the URL path.
When organizing your app so each part has its own address.
When you want to control what users see based on the URL they visit.
Syntax
Express
app.METHOD(PATH, HANDLER)
// METHOD: HTTP method like get, post, put, delete
// PATH: URL path string or pattern
// HANDLER: function to run when route matchesUse app.get() for handling GET requests (like loading a page).
The HANDLER function receives request and response objects to work with.
Examples
This route sends 'Home page' when someone visits the root URL.
Express
app.get('/', (req, res) => { res.send('Home page') })
This route handles form submissions sent to '/submit' using POST method.
Express
app.post('/submit', (req, res) => { res.send('Form submitted') })
This route captures a user ID from the URL and shows it.
Express
app.get('/users/:id', (req, res) => { res.send(`User ID: ${req.params.id}`) })
Sample Program
This simple Express app uses routing to send different messages for the homepage, about page, and a personalized hello page based on the URL.
Express
import express from 'express' const app = express() const port = 3000 app.get('/', (req, res) => { res.send('Welcome to the homepage!') }) app.get('/about', (req, res) => { res.send('About us page') }) app.get('/hello/:name', (req, res) => { res.send(`Hello, ${req.params.name}!`) }) app.listen(port, () => { console.log(`Server running at http://localhost:${port}`) })
OutputSuccess
Important Notes
Routing keeps your app organized by separating what happens at each URL.
Order of routes matters: Express checks routes top to bottom and uses the first match.
Use parameters (like :name) to capture parts of the URL dynamically.
Summary
Routing connects URLs to code that sends responses.
It helps build websites and APIs that respond differently based on the address.
Express makes routing easy with simple methods like app.get() and app.post().