johnwj
johnwj

Reputation: 449

Getting parts of a path in node.js

I have an array of people as follows:

people = ['personA', 'personB', 'personC'];

I want to be able to display a page about the person based on the url. For example, localhost:3000/people/personA would direct me to a page about personA.

How do I do so without having to specify the following multiple times for each team member? Is there a way I can grab the part after '/people/'?

  app.get('/people/personA', (req, res) => {
     // render view for personA
  }
  });

Upvotes: 1

Views: 65

Answers (2)

Anurag Goel
Anurag Goel

Reputation: 468

here is the solution

app.get('/people/:person', funcation (req, res){
    res.render("views/"+req.params.person+".html"); 
  }
});

Upvotes: 0

Mate Hegedus
Mate Hegedus

Reputation: 2905

You should do it with a parameter in the url. You can add a parameter using :param_here and get its value using req.params.param_here Like so:

app.get('/people/:person', (req, res) => {
    var person = req.params.person; // Variable telling you which person to show
  }
});

Upvotes: 1

Related Questions