Using placeholders in ExpressJS routing

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Starting with the code from our first ExpressJS app linked here, we now want to use placeholders in ExpressJS routing.  Let’s add the following code  …

routing with placeholders

routing with placeholders

In the route …

app.get(“/blog/:id”)

the colon id is the placeholder.  Express will put the matched placeholder on req.param.  req.param is a function that takes a parameter.  Here we pass it the parameter “id” and it will pull the value from the placeholder “:id”.

Now when we run, we can type in a path with a number 5 as shown…

expressjs routing with placeholder

expressjs routing with placeholder

ExpressJS is able to pickup this number from is placeholder of “:id” and display it in the output.

The placeholder can have something following after it (for example a file extension).

app.get(“/blog/:id.html”)

Now …

another example of routing with placeholder

another example of routing with placeholder