Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Michael Williams
PLUS
Michael Williams
Courses Plus Student 8,059 Points

How do I get my splat route matcher to work with my dictionary? (NOTE: This is an Express question.)

I'm tinkering with Express and creating a random app that repeats a word that's typed into the URL a certain number of times. For both the word and the number of times to repeat it, both of those are unknown until it's typed into the address bar. To accomplish this, I'm using patterns/route markers. It works flawlessly for any path I type, except when I type a path with an :animal that hasn't been defined (i.e. "blah.com/speak/wolverine"). When that happens, I get an undefined message instead of my catchall statement. I've have also tried (based off nothing but a hunch) app.get("/*/*", ...) with the hope that'd fix it. But no such luck. So:

1) Why does it not use the splat route marker for an undefined dictionary item? 2) How do I get it to use the splat route marker for said item?

var express = require("express");
var app = express();

app.get("/", function(req, res){
    res.send("Hi there, welcome to my assignment!");
});

app.get("/speak/:animal", function(req, res){
    var sounds = {
        pig: '"Oink"',
        cow: '"Moo"', 
        dog: '"Woof Woof!"',
        cat: '"I hate you, human!"',
        goldfish: '"I already forgot what you said."'
    }
    var animal = req.params.animal.toLowerCase();
    var sound = sounds[animal];
    res.send("The " + animal + " says " + sound);
});

app.get("/repeat/:message/:times", function(req, res){
   var times = Number(req.params.times);
   var message = req.params.message;
   var word = "";
   for (var i = 0; i < times; i++){
        word += " " + message;
        }
   res.send(word);

});

app.get("/*", function(req, res){
    res.send("Sorry, page not found... What are you doing with your life?");
});

app.listen(process.env.PORT, process.env.IP, function(){
    console.log("It's alive! It's aliiiiiiiiive!!");
});

NOTE: I'm using Cloud 9, hence the two arguments in the app.listen method of the code, hence the non-numerical port number.