CLOSE

Routing in Express

Routing in Express lets us define how the application responds to client requests for specific endpoints (URIs) and HTTP methods (e.g., GET, POST). With Express's routing system, we can easily map URL patterns to callback functions that handle the request and produce a response.

Defining Routes

Routes are defined using methods corresponding to HTTP verbs, such as:

  • app.get()
  • app.post()
  • app.put()
  • app.delete()

Each route takes at least a path and a callback function.

For example:

const express = require('express');
const app = express();

// Define a simple GET route for the home page
app.get('/home', (req, res) => {
    res.send('Welcome Home!');
});

This code listens for GET requests at /home and responds with "Welcome Home!".

Route Parameters

Route parameters are named segments in the URL that begin with a colon (:). Their values are accessible via req.params.

Example:

// Define a route with a dynamic user ID
app.get('/users/:userId', (req, res) => {
  const userId = req.params.userId;
  res.send(`User ID: ${userId}`);
});

A request to /users/42 would set req.params.userId to "42".

Optional Parameters

We can make parameters optional by appending a question mark (?) to the parameter name.

Example:

// Define a route with an optional postId
app.get('/posts/:postId?', (req, res) => {
  const postId = req.params.postId;
  if (postId) {
    res.send(`Post ID: ${postId}`);
  } else {
    res.send('No Post ID provided');
  }
});

Regular Expression Routes

Routes can also be defined using regular expressions for more complex matching.

Example:

// Match routes like /items/123 using a regular expression
app.get(/^\/items\/(\d+)$/, (req, res) => {
  const itemId = req.params[0]; // The first captured group
  res.send(`Item ID: ${itemId}`);
});

Query Parameters

Query parameters are not part of the route path but are appended to the URL (e.g., ?q=searchTerm). They are accessible via req.query.

Example:

// Handle query parameters for search
app.get('/search', (req, res) => {
  const query = req.query.q;
  res.send(`Search query: ${query}`);
});

Complete Example

const express = require('express');
const app = express();
const port = 3000;

// Simple static route
app.get('/home', (req, res) => {
  res.send('Welcome Home!');
});

// Route with a required parameter
app.get('/users/:userId', (req, res) => {
  const userId = req.params.userId;
  res.send(`User ID: ${userId}`);
});

// Route with an optional parameter
app.get('/posts/:postId?', (req, res) => {
  const postId = req.params.postId;
  if (postId) {
    res.send(`Post ID: ${postId}`);
  } else {
    res.send('No Post ID provided');
  }
});

// Route defined using a regular expression
app.get(/^\/items\/(\d+)$/, (req, res) => {
  const itemId = req.params[0];
  res.send(`Item ID: ${itemId}`);
});

// Route to handle query parameters
app.get('/search', (req, res) => {
  const query = req.query.q;
  res.send(`Search query: ${query}`);
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});