Get Route Parameter Input from the Client

Please help.

I have done this lesson - the only way I could get it to work was to comment out my previous code - so my code looks like this:

Spoiler
const mySecret = process.env['MESSAGE_STYLE']
let express = require('express');
let app = express();
console.log('Hello World');
//app.get('/', (req, res) => res.send('Hello Express'));
// app.get('/', (req, res) => res.sendFile(__dirname + '/views/index.html'));
// app.use('/public', express.static(__dirname + '/public'));
// app.use((req, res, next) => {
//   console.log(req.method + " " + req.path + " - " + req.ip);
//   next();
// });
// app.get('/json', (req, res) => res.json(process.env.MESSAGE_STYLE == 'uppercase' ? {"message": "HELLO JSON"} : {"message": "Hello json"}));
// app.get('/now', function(req, res, next) {
//   req.time=new Date().toString();
//   next();
//   },
//   function(req, res, next) {
//     res.json({"time": req.time});
//   }
// );
app.get("/:word/echo", (req, res) => {
  res.json({
    "echo": req.params.word
  });
});
module.exports = app;

I have two questions here:

  1. How do I see my results? my link is https://boilerplate-express.alanbra.repl.co and I tried looking at https://boilerplate-express.alanbra.repl.co/echo and https://boilerplate-express.alanbra.repl.co/freecodecamp/echo but both just showed Not Found
  2. Why didn’t my code work without commenting out my previous code - the lesson didn’t say anything about this - I only commented it out after someone on the forum had said they’d commented out their code

Thank you
Alan

This https://boilerplate-express.alanbra.repl.co/freecodecamp/echo returns an object.

{
  "echo": "freecodecamp"
}

Also, your code passes for me even if I comment back in all the code.

Weird - it also now works for me - I started looking at the next lesson, saw I had a reply from you, went back to my https://boilerplate-express.alanbra.repl.co/freecode/echo which then gave me the object and so I then went to my code and commented back all the code and resubmitted it and it worked. Don’t know what’s happening, but it’s working now

Hard to say, maybe you had an error you didn’t notice? Usually when commenting out code makes some other code work the code has errors in it.

There is one exception in Express code which is if you have two routes using the same path and method. Then the first will work and the second will not (well it works, it just doesn’t run).

app.get('/json', (req, res) => {
  res.json({ name: 'John'})  
})

app.get('/json', (req, res) => {
  res.json({ name: 'Jill'})  
})

Path /json === { name: 'John'}

Sort of the reverse of how it works in JS, there the last of two functions named the same will be the one that runs.

function echoName(name) {
  return 'I do not get to talk to ' + name;
}

function echoName(name) {
  return 'Hello ' + name;
}

console.log(echoName('John')); // Hello John

In any case, at least it works now.