Express: Handling Routes with Skyrim 🐉 ⚔️ 🪄

Sam Lesser
6 min readApr 24, 2021
Created by: 7Legionarmy 😎

Pre-Introduction

Before you dive into this blog, please make sure you have a good foundation on the following topics. I won’t spend much time on concepts about express.js, node.js, etc. If you are looking for more of a basic understanding, check out some of the blogs I’ve written on the topic. They’re super fun and easy to read.

What you’ll need 🧰1. Understanding of Express.js basic setup2. Response + Request Cycle3. Express.js Middleware — — — — — — — — — — — — — — -Helpful Blogs 🧙‍♀️ 📜 🪶1. Express.js: https://ineedmoreplates.medium.com/express-js-learn-with-p-e-memes-bfa080b5a9182. Middleware Functions: https://ineedmoreplates.medium.com/learn-express-js-middleware-functions-mario-bros-6b8d8214cc32

Introduction

Hello fellow reader, super excited to write about this blog today. I’m a huge elder scrolls dork 🤓 and I’d like to combine my passion for fantasy writing/RPGs with a simple explanation about routing in Express.js. I Will touch on the basics in this blog using The Elderscrolls video game Skyrim to contextualize the concepts. For those of you unfamiliar with Skyrim or the Elderscrolls universe, fear not! Skyrim is just the flavor, and not the “Meat n’ Potatoes” of the concepts.

What’s Routing? 🤔

Long way to Markarth from here… ⚖️ 😓🚶
“Routing is the process of selecting a path for traffic in a network or between or across multiple networks. Broadly, routing is performed in many types of networks, including circuit-switched networks, such as the public switched telephone network (PSTN), and computer networks, such as the Internet.”- Wikipedia

Well, to put it bluntly, it’s how you get around your web application. We need to select a path to get from point A to point B. Unless you want a single static page you’ll need to be able to make an application that a user can explore.

Let’s take a look at the code I wrote about middleware functions from my last blog. If you recall, we need to create middleware to handle incoming responses using an Express pattern. The response hits the top middleware first and only moves on to the next one if the .next() is invoked.

in app.jsconst express = require(‘express’);const app = express();app.use(😯 ‘/’😯 ,(req,res,next) => { ← first argument is a path😯next() ← go to next middleware 🥾 🥾 🥾});app.listen(3000);

This is the logic behind handling our routing. We set up our middleware with different paths, which will funnel from one to the next. Once our request matches the correct middleware will fire off whatever is inside the function.

Traversing Skyrim

50 septim !!!! In this economy? No thanks, buddy I’ll walk! 😡 💼 🏃

Let’s have a little thought experiment to help illustrate the routing process using Express.js. Let’s say we are planning a trip to “The Reach” from “White Run”. If we traveled on foot it would take forever so let’s grab a carriage outside town. How would Express middleware handle this peril-less journey? Certainly not with a loading screen!

Will first need to install an NPM package called body-parser. This package is an abstraction to handling streaming data and using a buffer. The main idea being we have a standardized way to work on the incoming data and preparing it. Giving us less code to work about during the debugging process.

In terminal 🧑‍💻npm install — save body-parser — — — — — for reference 👀Dragonbones 🐉 🦴 🪙weight: 15Base Cost: 500. ←- That’s really good 💰

Think of it this way, we are traveling to The Reach. We know the merchant there are prepped and eager to buy dungeon loot. The only problem is we have a ton of dragon bones. Which weighs us down, so no fast travel and you can forget walking.

Whiterun does have a carriage driver, which can take us there for a fee. Yet we can’t carry it all in one shot, so they being to make trips.

As your luggage arrives, your trusted housecarl, Lydia will unpack and organize each shipment. Lydia DOES NOT have to wait for all the Dragonbones to come over, that’s not efficient. Instead, she gets started organizing the shipments upon arrival so we don’t waste time. Super convenient! Thanks, Lydia!!!

Best Housecarl ever!!! 🥇 🏆 👏

This essentially is what we are doing with body parsing. We read the incoming request and as it arrives in pieces we are organizing it so that we don’t have to wait for the whole request to come through.

Now that we have installed our NPM package let’s import it on the app.js level. After this, will create a middleware. Since every route will require a parser let’s create it on the top of all our routes. This way we parse all data coming in THEN we match it to a route.

Let’s implement a body-parser and a few routes. Let’s imagine that each middleware is a city in Skyrim. When we arrive in that city, we should be greeted with some HTML using the response argument and the .send() method.

To simulate the delivery of dragon bones, let’s make a form in Whiterun. We will use some HTML and

this…

in app.jsconst express = require(‘express’);const app = express();const bodyParser= require(‘body-parser’) ← Import here 😯app.use(bodyParser.urlendcoded({extended: false})) ← bodyparser 😯app.use(‘/’ ,(req,res,next) => {next()});app.use(‘/markarth’ ,(req,res,next) => { ← we want to go here 🐎res.send(‘<h1>Greetings from Markarth!!!</h1>’) ← sends a response, html code 😯});app.use(‘/whiterun’ ,(req,res,next) => {res.send(‘<h1>Welcome to White Run!!!</h1><form action=”/markarth” method=”POST”><input type=”text” ><button></form>’ ←- enter what’s being shipped !});app.use(‘/winterhold’ ,(req,res,next) => {res.send(‘<h1>Greetings from Winterhold!!!</h1>’)});app.listen(3000);

Notice the .urlendcoded() method that comes off of the body parser. We are choosing this method because it’s the right tool for this job. I encourage you to read a bit more about what our NPM Package: body-parser offers. You may find you’ll need something different based on what you are trying to accomplish.

Let’s talk about this syntax, we invoke it so we can initiate the parsing of any incoming responses’ body. We are also passing it an object with a key of extended and it’s set to false. We do this to allow non-default objects and arrays to be encoded into the URL-encoded format.

You can read more about this in the links below, it never hurts to read into syntax for deeper understanding. Please don’t take syntax at face value, shying away from docs, in general, isn’t a good practice. Dig into it. Explaining your own code is an important skill, so don’t just copy and paste, try to understand!

Now that we have routes in place, greetings for each page, and a form on our Whiterun page, let’s send over some loot. Fire up your server, open a browser, and type in your Whiterun URL. Which should look like this…

Enter in your browser

localhost<YOUR PORT>/whiterun 🦴 🗡 🛡

This should load a simple page with a form, enter in dragon bones, or anything else you want to send to Lydia. Go take a look at your console you should see a Javascript object, with a key-value pair, the value is your entered item. Pretty cool right?

The body-parser + routing allows us to send data throughout our web app. It may seem like a trivial thing but understanding this fundamental will save you hours on debugging.

Conclusion

Housecarl… I need you to hold something for me 🧝

It’s a pretty simple pattern to understand. Yet can be the source of some bugs when you’re starting out. Take some time to understand these basics. Test things out, break them, and understand what went wrong. It’s all learning so don’t be afraid to get messy!

I hope this was a helpful read, please stay tuned 📺 as I write a new technical blog every week. Happy coding 👩‍💻 👨‍💻 🧑‍💻

Check out these links! 😎
Cool Links Here:Express Docs on Routing: https://expressjs.com/en/guide/routing.htmlWiki Link (Routing): https://en.wikipedia.org/wiki/RoutingbodyParser npm: https://www.npmjs.com/package/body-parserMore on .urlencoded(extended: false) https://github.com/expressjs/body-parser#bodyparserurlencodedoptionsReddit post about 7Legionarmy’s artwork: https://www.reddit.com/r/inkarnate/comments/d6486y/skyrim/

--

--

Sam Lesser

Career Changer, Software Engineer & Web Developer