Understanding Routes in an Express App

Ethan Jarrell
codeburst
Published in
3 min readJul 6, 2017

--

Routes were one of the difficult things to wrap my head around in the first week or two of back end programming. But, for anyone who is also struggling with app.get and app.post and routes, I’ve made a few visuals, to show how they all work together. I’m working on a project now for a social networking site called Gabble. Below, is my my index, or root page. I have my index.js as well as my index.mustach pulled up, so you can see how those pieces fit together when rendered in Chrome. Take a look:

In my index.js I’ve used the app.get method to distinguish this as my root page with “/”, and then have told the browser to render my “index” page, which I have defined in my mustache file. See, it’s not that bad, right? Okay, so once someone clicks on the login page, what happens? I’m glad you asked that question. Let’s take a look:

As you can see, in Chrome, the localhost:3000 has added a route, and we are now at localhost:3000/login. login.mustache is our login view. We have also created both an app.get to render the login page the same way we did our index page. But here, we’ve also added an app.post, where we’re authenticating users. In our mustache file, the input fields have a name of username and password, and we are using those distinct names in our index.js file as req.body.password and req.body.username inside the app.post to reference those fields. Then on line 91 in index.js, once they log in, they are redirected to ‘/home’. For me, it really helps to see everything visually like this. Okay, now let’s take a look at what happens when they are re-directed. Here’s the home page:

As you can see, now we are on localhost:3000/home. We are also doing an app.post here, so that we can build this display of all the recent gabs that a user has made. These gabs include a title and a post, which we’ve created and stored in a database. In our mustache file, we are pulling that data from the database and displaying it using the mustache brackets. We’re also doing something interesting here online 22, where we are using mustache to add a welcome banner, so it says “Welcome, + ‘username’”, as well as “Logged in as + ‘username’ “. We’re doing all that work through mustache, pulling the data from our database. In these brief examples you can see that the app.get renders information on a page, but in a case where we need to add data to our database from user input, we need to use the app.post method. Making sure you have the same routes in your index and mustache files is also vital to making sure the user is re-directed to the right pages.

I hope this brief visual has been helpful. Feel free to reach out to me if you have any questions or feedback. Thanks!

--

--