DEV Community


Node.js Under The Hood Routes vs Express Routes

greedybrain profile image Naya Willis ・2 min read

So, I've been learning Node Js recently. It's been a little on and off but I'm still pushing through when I can. So far I'm really enjoying it. I'm actually learning it from one of my favorite developers. His name is Mosh. He has a very straightforward way of explaining things. I've actually used his videos in conjunction with another developer who goes by the handle The Net Ninja. He's pretty straightforward as well.

I really enjoyed how The Net Ninja starts off showing you what's going on under the hood in is Node.js series. For example, defining your routes without using express would include you using either a switch case, or an if else block. It'll look a little something like this.

Alt Text

The req.url is basically the condition. We want to check if any of the following cases match this condition. If we get a match we add the .html file to the value of path so that html can be rendered. Basically, the path variable is "./views/". Which tells the application where to look for the corresponding .html file. In this case it's our views folder.

On the other hand you have express which provides us some middleware functions such as app.use, app.get, etc. This makes our routing a bit more cleaner and to be honest I find it quite fun. To set up routing with express we basically do the following

  1. Install express => npm i express
  2. Import it => const express = require('express')
  3. Invoke it, returning the value and setting it as the value of a variable named app (by convention) => const app = express()
  4. Start defining those routes like so
app.get('/', (req, res) => {
     res.send('This is the root page')

app.get('/about', (req, res) => {
     res.send('This is the about page'
Enter fullscreen mode Exit fullscreen mode

And so on. Clearly we see that this is more fun than using a regular switch statement or if and else block.

Learn some Node my friends. If you aren't already.

Discussion (0)

Editor guide