Express Routes And HTTP Requests

In previous posts I've shown how to use the express framework to create a website and how to use pug templates to generate HTML markup.

Now it's time to talk about routes.

Let's have a look at our simple express app again. Here's index.js:

var express = require('express')  
var app = express()  
app.set('view engine', 'pug')

app.get('/', function (req, res) {  
    res.render(
        'index',
        { title: 'Hey Hey Hey!', message: 'Yo Yo'})
})

app.listen(3000, function () {  
    console.log('Example app listening on port 3000!')
})

and here's our pug template:

html  
  head
    title= title
  body
    h1= message

What exactly does app.get do anyway?

I'll tell ya. :)

It's a function that takes two parameters: a string, and a callback function. The string specifies a path for your site. The callback function allows you to specify what the end user will get for that path.

For example, if I add this to index.js:

app.get('/monkey/bear/potato', function (req, res) {  
    res.render(
        'index',
        {
            title: 'Monkey Bear Potato!',
            message: 'Carrots'
        })
})

And then go to http://localhost:3000/monkey/bear/potato in my browser. I'll see a page that tells me the oh-so-enigmatic message: "Carrots".

Basically, app.get allows me to specify any path for my web site and then determine what happens when a user gets there.

I can even grab pieces of the url. Check this out:

app.get('/monkey/bear/:potato', function (req, res) {  
    res.render(
        'index',
        {
            title: req.params.potato,
            message: req.params.potato
        })
})

When I go to http://localhost:3000/monkey/bear/kermit-the-frog I see a page with the title of kermit-the-frog and an h1 element that shows kermit-the-frog.

req.params will hold the value of any url parameters I specify:

app.get(  
    '/monkey/bear/:potato/:robots',
    function (req, res) {
        var thing =
        `${req.params.potato} ${req.params.robots}`
        res.render(
            'index',
            { title: thing, message: thing})
    })

Now http://localhost:3000/monkey/bear/kermit-the-frog/miss-piggy takes me to a page speaking of the love that only a frog and pig can share!

app.get handles what are called HTTP requests, specifically GET requests. Those are the kind that the browser usually makes when you type a url in the address bar and hit enter.

There are other HTTP request types:

app.post('/monkey/:name', function (req, res) {  
    res.json({
        new_monkey: 'Monkey!',
        name: req.params.name
    })
})

POST requests are usually reserved for adding some data to an app's back end database. If you use something like postman you can test this out by making a post request to http://localhost:3000/monkey/supermonkey. You should get the response:

{"new_monkey":"Monkey!","name":"supermonkey"}

I also changed things up and started using res.json to send back JSON data (a data format that matches JavaScript object format almost exactly) instead of HTML.

I'll be writing a lot about web applications on this blog and JSON is the primary way that a JavaScript front-end will be talking with its backend.

There are other HTTP request types: DELETE, PUT, PATCH, all meant to do some specific thing on the server. You can read more about them here.

Express has matching functions for each of these request types (app.delete, app.put, app.patch, etc.)

Of course, your app could use DELETE to add something and PATCH to remove something. No one is stopping you from doing it wrong. The Internet police will not fine you for PUT-ing when you should have POST-ed. :)

Another cool thing about POST and some of these other requests is that you can send data along without putting it in the address bar:

var express = require('express')  
var app = express()  
var body_parser = require('body-parser')

app.set('view engine', 'pug')  
app.use(body_parser.urlencoded({extended: false}));  
app.use(body_parser.json());

app.put('/robot', function (req, res) {  
    res.json({
        name: req.body.name,
    })
})

app.listen(3000, function () {  
    console.log('Example app listening on port 3000!')
})

To use this you'll need to npm install body-parser and add a key-value pair in postman with name as your key.

I chose "optimus prime" and got back:

{"name":"optimus prime"}

The take-away I'd like you to get from this is that it's pretty easy to set up any url path you want for your app and use HTTP requests to organize the data you send back and forth between the front and back ends of the web applications you build.

Looking for a software developer?