The Web Developer Bootcamp 2024

Colt Steele

Back to Express Index Page


 

Express Js
Routing
Recap

So far we have learned how to get our server up ands running, and then start the server and check the output. Here is the server code:

  • JavaScript
  • index.js
  • const express = require('express');
  • const app = express();
  • const port = 3000
  • // response for requests to the root URL (/)
  • app.get( '/', ( req, res ) => {
    • res.send('Hello World!');
  • })
  • // starts the server : listens for response
  • app.listen( port, () => {
    • console.log(`App Server is running : Listening on port ${port}`)
  • })

To recap, we:

  • ∴  required (imported) express : express
  • ∴  created a variable to represent the express object : app
  • ∴  created a variable to define the server port number : port = 3000
  • ∴  we started the server : app.listen
  • ∴  and the server should now be running and waiting for a response, on port = 3000.


Routing

So the server is up and running and waiting for a response. Now we can look at how to process the response. This is done with "routing". If we look at this line in our server code:

  • app.get( '/', ( req, res ) => {
you can see that we have '/'.

This is actually a path definition pointing to the root directory of our server. This is our routing. What this line of code is saying is that if we open a browser window and go to [http://localhost:3000/] (the server root), then whatever code was defined in this particular callback function, will run.

So naturally, we could define any other "routes" that we want. If we have an "About Us" page, the routing might look like:

  • app.get( '/about', ( req, res ) => {
    • res.send('This is the "About Us" page.');
  • })
or, if we had a "Login Page", it might look like this:
  • app.get( '/login', ( req, res ) => {
    • res.send('This is the "Log In" page.');
  • })
and so on, and so on.


Error Trapping

Another thing to mention here. If a req is sent that will return an invalid response, such as requesting a page that does not exist, the browser will display an error. A better solution is to include an "error trap" within our code to resolve this. So we've add the following code to our server code:

  • app.get( '*', ( req, res ) => {
    • res.send('Invalid Path : Path Not Found!');
  • })
If we make a request for anything that has not already been defined in the routing, then display the "Invalid Path : Path Not Found!" message. And remember, because of the "Top Down" nature of JavaScript, the error trap MUST go after all of the other routing, so that all of the other routing has a chance to work. And if none of the other routings work, THEN run the error code.


Group Routing

In our server code that we've written so far, we only have three different routes. One for the "Home" directory. One for an "About" directory. And one for a "Login" directory. But what if we were talking about a website such as Reddit that could have hundreds of different routings? We wouldn't want to define a routing for every single one. So we need a way to do a kind of "universal" routing. The way to do this is with Technique called "Path Parameters".

If you go to Reddit and search for, oh let's say "chickens". It opens a sub-reddit called "chickens". And if you look at the path in the address bar, you will see "https://www.reddit.com/r/chickens/". The important thing to note here is the /r/chickens/ designation. This is a path parameter.

Start by defining the path parameter in your get method, like so:

  • app.get( '/r/subreddit', ( req, res ) => {
    • res.send('This is a Sub-Reddit');
  • })

Now, if we are using path parameters to control our routing, then we probably don't want a generic message like "This is a Sub-Reddit". And we can change this messaging using the params property of the req object. We can see tre output of this property by adding the code:

  • console.log(req.params);
and for our /r/chickens/ example we would get:
  • { subreddit: 'chickens' }
so the param name is subreddit, and the value is chickens, so we can rewrite our res.send code with a string temporal literate like so:
  • app.get( '/r/subreddit', ( req, res ) => {
    • const { subreddit } = req.params;
    • res.send(`Now browsing the ${subreddit} subReddit`);
  • })

One other note of importance here. Reddit is using the /r identifier and the subreddit variable, but we can use anything we like. For example, I'm using the /d designator (short for sub directory), and subDir as a variable name, so my code looks like this:

  • app.get( '/d/subDir', ( req, res ) => {
    • const { subDir } = req.params;
    • res.send(`Now browsing the ${subDir} sub directory`);
  • })

So if you are in my webpage and you type /d/anything in the address bar, the webpage will output:

  • Now browsing the anything sub directory

So when we are using path parameters we are defining a pattern, as opposed to defining an exact match, such as /about. And this can be used to route multiple responses so we don't have to manually define our multiple routes.


Back to Top