Routing Basics

A route connects an HTTP method and URL path to a handler function.

Syntaxapp.get(path, (req, res) => { ... })

Routing decides which code runs for a given request. A route has three parts: an HTTP method (like GET), a path (like /about), and a handler function.

When a request matches, Express calls your handler with req and res. Whatever you send with res becomes the response.

Anatomy of a route

  • app.get — the method to match.
  • '/about' — the path to match.
  • (req, res) => { ... } — the handler.

Example

Example · javascript
const express = require('express');
const app = express();

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 us'));

app.listen(3000);

When to use it

  • An e-commerce site defines separate routes for /products, /cart, and /checkout, each handled by a dedicated function.
  • A blog platform maps GET /posts to a list view and GET /posts/:id to a single post view using Express routing.
  • A developer uses Express routing to version an API, grouping /api/v1 and /api/v2 routes under separate routers.

More examples

Two basic routes

Registers two GET routes on the app object, each responding with a different string.

Example · js
const express = require('express');
const app = express();

app.get('/', (req, res) => res.send('Home'));
app.get('/about', (req, res) => res.send('About'));

app.listen(3000);

Route for multiple paths

Loops over alias paths and redirects them all to the canonical root route.

Example · js
const express = require('express');
const app = express();

['/home', '/index', '/'].forEach(path => {
  app.get(path, (req, res) => res.redirect('/'));
});

app.get('/', (req, res) => res.send('Welcome!'));
app.listen(3000);

Wildcard catch-all 404 route

Adds a final catch-all middleware after all named routes to return a 404 JSON response for unknown paths.

Example · js
const express = require('express');
const app = express();

app.get('/', (req, res) => res.send('Home'));
app.get('/about', (req, res) => res.send('About'));

// Must be last
app.use((req, res) => {
  res.status(404).json({ error: 'Route not found' });
});

app.listen(3000);

Discussion

  • Be the first to comment on this lesson.