02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Routing with Express

Routing with Express.js

In this tutorial, we'll explore the basics of routing in Express.js, an essential component that transforms a simple server into a dynamic, interactive platform. Express.js is a popular framework built on top of Node.js that provides an easy way to manage server-side logic.

What is Routing?

Routing refers to the process of defining and managing the paths through which clients can interact with the server. By defining routes, we can serve different content based on the client's request, making the server dynamic rather than just serving static content. This capability allows us to create interactive websites, APIs, and more.

In this tutorial, we'll be working with the following HTTP methods:

  • GET: Typically used to request data from the server. For instance, accessing a web page.
  • POST: Used to submit data to the server, such as submitting a form.
  • DELETE and PUT: Used to delete or update existing data, respectively. These are less common but useful for specific applications, particularly in RESTful APIs.

Setting Up Routes in Express.js

To add routes to an Express.js application, you can use the app.get(), app.post(), app.put(), and app.delete() methods.

In the example below, we start by setting up a GET route for the root (/) path of our application, which simply responds with a "Hello World" message when a client visits that URL.

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

// Basic GET Route
app.get('/', (req, res) => {
    res.send('Hello World');
});

// Start the server
app.listen(3006, () => {
    console.log('Server is running on port 3006');
});

In this case, when the server receives a GET request at the root URL (/), it responds with "Hello World".

Dynamic Routes

Routing can be even more powerful when combined with dynamic content. For example, imagine setting up a blog application where each blog post has a unique ID. We can use parameters in the URL to serve different content based on what the client is requesting.

app.get('/blog/:id', (req, res) => {
    const blogId = req.params.id;
    res.send(`You are viewing blog post ${blogId}`);
});

In this example, when a client visits /blog/1, they will see the response: "You are viewing blog post 1". The :id parameter is dynamic, meaning that we can replace it with any value, and Express will handle it accordingly.

Handling Multiple HTTP Methods

In many scenarios, the same URL can be used for different purposes. For instance, you may want a GET route to display a form and a POST route to submit that form.

To simplify these cases, Express.js allows chaining of HTTP methods using the app.route() method.

app.route('/form')
    .get((req, res) => {
        res.send('Display form');
    })
    .post((req, res) => {
        res.send('Form submitted');
    });

This allows us to group multiple methods for the same path together, making the code easier to read and maintain.

Using Wildcards and Regular Expressions in Routes

Express also provides advanced routing capabilities, including the use of wildcards (*) and regular expressions to match patterns in URLs. This allows developers to handle more complex route requirements.

  • Wildcards: Using * allows you to match any number of segments. For example, you could create a catch-all route to handle 404 errors.
  • Regular Expressions: For more specific matches, you can use regular expressions.

These tools provide flexibility when building routes to make sure that your application can respond correctly in a variety of scenarios.

Summary

Routing is at the core of server-side development with Express.js. In this tutorial, we've covered:

  • The basics of setting up routes with Express.
  • Defining GET, POST, DELETE, and PUT routes.
  • Creating dynamic routes with URL parameters.
  • Using app.route() to chain multiple methods.
  • How to leverage wildcards and regular expressions to enhance routing.

With this foundation, you're ready to start building dynamic, interactive applications using Express.js routing.

In the next section, we'll dive into how to respond with static files and further enhance the capabilities of your Express server.

Note: This video was created in 2016. Since then, new features may have been added to Express.js, and best practices may have changed. Please make sure to check the official Express.js documentation for the latest updates and improvements.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!

Starting up an Express.js server

Learn how to start up an Express.js server, including installation, basic setup, and creating a Hello World server.

08:08

Enabling static files

Learn how to enable static files in Express.js to serve HTML, CSS, JavaScript, and other assets in your web application.

04:47

Routing with Express

In this video, explore the basics of routing in Express.js and how to create dynamic content. Learn about GET, POST, PUT, DELETE, and how to handle different routes effectively.

09:08

Routing with Forms and Static Files in Express.js

Learn how to create dynamic routes with forms and static files using Express.js. This is essential for building interactive web applications.

06:14

Using Middleware in Express.js

Learn how to integrate third-party middleware in Express.js, specifically using body-parser, to handle form data and extend server functionality.

07:29

Creating a middleware in ExpressJS

Learn how to create your own middleware in ExpressJS to handle custom server-side logic and responses.

03:54

Using Express Generator

Learn how to quickly scaffold Express.js applications using the Express Generator tool. This tool helps automate server setup and structure, making development faster and easier.

04:34

Back to React

Learn about integrating Webpack and Babel with React to streamline full stack development.

18:16