URL Parameters in Express.js
Posted on August 22, 2016 in Node.js by Matt Jennings
Example of a URL parameter that uses Express.js
// Route for each poll
// and ":poll_id" is a URL parameter where a value passed the to URL,
// like "example.com/polls/1234" is passed in as the "req.params.poll_id" value
// below
app.get('/polls/:poll_id', function(req, res) {
var get_poll_id = req.params.poll_id;
console.log(get_poll_id);
res.send(get_poll_id);
});
app.get('/tester', function(req, res) {
// Below I'm passing in a JSON object (or hash table of keys and values, which is similar to an associative array)
// as a 2nd parameter to the "tester.handlebars" template
res.render('tester', {
first_name: "Donald",
last_name: "Duck",
now: new Date(),
random_num: Math.round(Math.random() * 10)
});
});
Website Output if you go to example.com/polls/1234
1234