Express Route Handlers

Introduction

Imagine you're running a post office. Every letter or package needs to be routed to its destination. Express works similarly, acting as the routing system for your web server. In this guide, we will configure Express routes to handle client requests, building on your knowledge of Node's http package.

You'll learn how to handle the following HTTP request types:

Setting Up Express

Let’s begin by creating a simple Express application:

const express = require('express');

const app = express();

// Define routes
app.get('/', (req, res) => {
    res.send('Hello from Express!');
});

app.post('/users', (req, res) => {
    res.send('User created!');
});

// Start the server
const port = 8081;
app.listen(port, () => console.log(`Listening on port ${port}...`));

Key Steps:

  1. Create the Express server using express().
  2. Define routes with app.get(), app.post(), etc.
  3. Start the server with app.listen().

Understanding Routes

A route in Express is like a traffic signal directing requests to the right path. Each route matches:

Here's an example:

app.get('/welcome', (req, res) => {
    res.send('Welcome to our site!');
});

The req (request) object provides details about the client's request, while the res (response) object allows you to send data back.

Dynamic Route Paths

Routes in Express can be dynamic:

Example:

let paths = ['/', '/about', '/contact'];

app.get(paths, (req, res) => {
    res.send('This works for multiple paths!');
});

Designing Routes

Good route design makes your application intuitive. Consider these examples for a Twitter-like app:

Path HTTP Verb Description
/tweets GET Retrieve all tweets
/tweets POST Create a new tweet
/tweets/:id GET Retrieve a tweet by ID

Sending Responses

Use the res object to send responses:

Example:

app.get('/json', (req, res) => {
    res.json({
        message: 'Hello, JSON!',
        status: 'success'
    });
});

Testing Your Routes

To test your Express application:

  1. Run your app with node app.js.
  2. Visit http://localhost:8081 in a browser (for GET requests).
  3. Use tools like Postman or Fetch API for other methods:
fetch('/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username: 'NewUser' })
}).then(res => res.json()).then(console.log);

Real-World Applications

Express routes are foundational for:

Example: A task management app could use routes like: