After setting up a new project folder and initializing NPM in the Node.js repl, I proceeded to install the Express package. In my JavaScript file, I included the following code:
const express = require('express');
const app = express();
app.listen(5000, function(){
console.log("server started on port 5000");
})
app.get("/", function(req, res){
res.send("Hi There! Welcome!")
})
app.get("/speak/:animalName", function(req,res){
var animalName = req.params.animalName;
var sound = "sound";
if (animalName === "pig"){
sound = "oink"
} else if (animalName === "dog"){
sound = "bau"
} else if (animalName === "cat"){
sound = "Miao"
}
console.log(req.params);
res.send("THE " + animalName + " says " + sound);
})
app.get("*", function (req, res){
res.send("Sorry, the page cannot be found")
})
Upon running the server with Nodemon, everything seems to work correctly. However, when entering a specific pattern in the URL field, although the console.log displays the req.params correctly (for instance, typing "cat" returns { animalName: 'cat' }
), the response in the browser is not as expected: