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.

Video Transcript

00:00We ended our last lecture where we set up our
00:04express JS node js server to have static files.
00:09In this lecture we're gonna add one more layer,
00:11which really moves us into the dynamic nature of programming
00:15languages that are done on the server, when
00:17that is the capability
00:19to create dynamic content based on different URLs.
00:23So we're gonna take a look at what routing is
00:25and get the basics of how to work with routings in
00:29and routes in this specific lecture.
00:31By the end of this lecture, we're gonna have little,
00:33some more familiarity with get posts
00:35and deletes, which are the different common commands
00:38that you could send from the client to the server.
00:42And this is gonna be really our first dynamic content.
00:44So let's jump right into it
00:45and let's see how to create routes in express js.
00:51Probably one of the most important features on a server side
00:55language is the capability to create dynamic content
00:58that is not derived directly at a static content.
01:03Now, if I go into our editor
01:05and I'm gonna un comment our app get,
01:08and I want to take a deeper look into what this is
01:11and what this is, is actually a route a routing rule
01:14that says whenever we approach this base location,
01:19that our root of our website, then do this
01:22really in this case because we're already taking over that
01:25inside of our public area.
01:26'cause we have there an index that HTML let's go ahead
01:30and create here something else.
01:32How about we create here a rule that says hello,
01:37hello, let's say hello.
01:39Do what?
01:40Should we do it just, nah, let's, let's,
01:43let's pretend we're html.
01:44How about that? Or even PHP, nah,
01:46let's not, let's not do that.
01:47Okay, so hello dot html.
01:49Now once I save this
01:51and we're gonna go back into the terminal, I'm,
01:54all I really want to do is I want to terminate our, uh,
01:57running operation and I I
02:00and notice that all I had to do that is terminate it
02:03and then rerun it and everything is working fine.
02:05And, and by the way, if you by mistake, instead of using
02:09Ctrl C and you used command C
02:12or um, really something else at any point
02:15and you got outta the application, but,
02:17or in any situation where you're running it
02:19and you're getting an arrow telling you, oh, this route,
02:22this route has already been taken in any situation like
02:25that, in this case we don't have that problem.
02:27But in any case like
02:28that would you would wanna do is call the kill all
02:32minus nine and then the name node.
02:35And what that will do is gonna kill all the different
02:37processes of node.
02:39Currently there are none, so we didn't find any.
02:41But in any situation where you want
02:43to continue using the port that you're using
02:46but you're stuck, then just go ahead
02:48and remember this shortcut.
02:49Kill all minus nine node
02:51and it'll get rid of all the applications.
02:53And by the way, don't do it if you're in a
02:56production environment where you're gonna kill
02:59All everything. In
03:00this case we're killing all the node,
03:01which is really something you're only gonna use in your
03:03development environment.
03:04Alright, with that said, let's run our node js again, now
03:09that it's running on our server,
03:10we're gonna go into the server
03:11and this time around, instead of approaching two html,
03:14which is a real file, I'm gonna go to hello at html,
03:17which is not a real file.
03:19And notice how we're getting the low world
03:22directly inside of our prompt.
03:23Now, routes don't have to be explicit just in this level.
03:28We could have even said, for example,
03:30let's say we want everything that's uh, let's say blog
03:34and anything that is blog html.
03:37So I'm putting here, uh, uh, anything, it could be anything.
03:39So I'm putting there on anything.
03:41And if I go ahead and restart my server again
03:44and I'm gonna go ahead there
03:45and exit the server, restart the server,
03:48go back into my application.
03:50If I go now into my blog area, first of all, it's not,
03:54you can't find blog, but if I go into blog
03:56and I try to find index html,
03:59now suddenly we have a low world
04:01and any element that we send here as long as it ends also
04:04with HTML, will re receive back.
04:06Now this is the way you create dynamic
04:09content really in a server side language.
04:13And by the way, there's not only get,
04:15I'm gonna put your oso a a, a few others,
04:17which we'll probably explore in fu future chapters
04:20or in future titles.
04:22But besides getting, there's four four, uh,
04:26functions really that you could use the get which is used
04:29traditionally just to get information.
04:31Your post, which is used usually in a form, not usually,
04:35usually in a form where you're sending information
04:37that usually has a lot of information, you're sending it
04:40with that form that you would use a post command, uh, put
04:44and a delete are two other options,
04:46which are very rare on the web, very rarely used.
04:49At least they're not as commonly used
04:51as the get and the post.
04:53Now I wanna show you just one more thing.
04:55By the way, you could use here a static string just defining
04:58exactly what you want.
05:00You could use here as you saw a star, there's a lot
05:03of other rules which are, are gonna be assigned.
05:06You could find inside of our documentation for the chapter.
05:09We could also use reg regular expressions
05:11if you know how to use them.
05:12That will really will elevate the amount of level
05:15and complexity of the rules that you're creating.
05:18Now I wanna talk about one more thing
05:20that will be a little bit vague at this point,
05:22and I apologize for that.
05:24But once you get to it, and if you're already familiar
05:27with the process of posting something in an HTML form,
05:30you'll know that there's two phases.
05:32The first phase is when there's nothing in the post,
05:34and the second phase is when there's something there.
05:36So the first phase is when you wanna show the form,
05:38and the second phase is something else that you wanna do.
05:41And those type of situations where you want
05:43to have a few different, uh, get a set
05:45and a few other things happening for the same URL for.
05:49So for example, maybe for everything in our blogs,
05:52we want OTO to have a get,
05:53but we also wanna have a post in case someone posts
05:55something into those areas.
05:58In those situations, I'm gonna go ahead
05:59and comment this out.
06:01Oh no, I'm gonna leave it the way it is
06:03and we'll create another one.
06:04How about that? So we're gonna create another one
06:06and I'm gonna go to my app and I'm gonna call it route.
06:08And what route does is not run
06:11or whatever I just wrote there route.
06:13And in the route I'm gonna define the rule, define the,
06:16the pathing that I want to have there.
06:18In this case, let's do this.
06:19How about we'll call this post
06:21and it's just gonna be called post just to confuse us,
06:25but really, or let's call this, um, form.
06:28So our form and step one is not,
06:30and the first step is not actually submitted yet.
06:33We want to present it on the second stage.
06:35We wanna actually maybe process it.
06:38So I'm gonna go ahead and I'm gonna continue.
06:40I'm not breaking, I'm chaining this route
06:42and I'm saying in the, in the scenario where it's a get,
06:45I want to create the same type of callback
06:47as we've seen previously.
06:49So in this case, in the situation where,
06:52and I'm just duplicating that a low world,
06:54but here, here really in the real world, you would see a,
06:58you would see a form.
07:02Now in this situation, I still want to continue
07:04because there may be a situation
07:06where we're actually posting when
07:07something actually comes back.
07:09And in that situation we're gonna go
07:11ahead and call the post.
07:12And the same applies.
07:14So we'll have your all the information
07:16and we would then be able to do whatever we want there.
07:18So in this case, um, this is the result
07:23of your submission of your, this is the result.
07:27How about that? Keep it short. All.
07:30So, and that, that's what we did when we chained in
07:32for the same route, all the different rules.
07:35Now by the way, the steps that are involved,
07:37they go progressively.
07:38So basically if there is something static
07:40that it's gonna be first
07:41because the first thing that we define
07:43and as we progress, the routes are chained in the order
07:46that, that they are received.
07:48So the priority would go for something that happened earlier
07:51versus something that happened later.
07:54So I'm gonna go ahead and save this
07:56and just test out that we could actually see our form
07:58that doesn't really have a form inside of it.
08:01But I'm gonna go ahead here and into my terminal
08:03and I'm gonna exit out of our current running application,
08:08rerun it and I'm gonna go into my browser,
08:10click on a refresh.
08:12We have a running browser
08:13and I'm gonna go to my form in this case, this is a get,
08:16so you would see here a form
08:18and you can see that we got our form, it's uh, running in
08:21and we're getting the get part of our form.
08:23Basically we could see this part, the get
08:25of the form is being processed in the route.
08:28We don't see yet the post,
08:30but we're gonna take care of that in the next lecture
08:32because in the next lecture we're also gonna look at
08:34how could we integrate static files
08:37and also be able to get through the process to be able
08:39to actually retrieve
08:41and get the relationship between this get
08:44and post to actually be visible to us
08:46as we're building up our application.
08:49In this lecture we explored routes
08:51and express js, which gets us very ready to move on
08:54to the next topic, which is
08:56how do we actually send only segments of content back
08:59to a server or to the client really in this point.
09:02So in the next lecture we're gonna learn on how to respond
09:05with static files as well.

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!