In the previous tutorial, we define routes, but those routes are static and fixed. In this post, we are going to learn about URL parameters and routing in Express.js. To use the dynamic routes, we should provide different types of routes. Using dynamic routes allows us to pass parameters and process based on them. The URL module splits up a web address into readable parts.

Topics Covered :

  • What is URL building?
  • What are dynamic routes?
  • What is pattern matched routes?

NOTE: To run the below mentioned code you must need to install express module.
 npm install express –save 

Here is an example of a dynamic route −

var express = require('express');
var app = express();

app.get('/:id', function(req, res){
   res.send('The id you specified is ' + req.params.id);
});

app.listen(2000);

To run this go to  http://localhost:2000/abc . The following response will be displayed.

The id you specified is abc

You can replace  ‘abc’  in the URL with anything else and the change will reflect in the response.
Lets us go with some complex example:

var express = require('express');
var app = express();

app.get('/things/:name/:id', function(req, res) {
   res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});
app.listen(2000);

Note: Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in thereq.params object, with the name of the route parameter specified in the path as their respective keys.

To run this go to  http://localhost:2000/things/pabbly/abcde.   The following response will be displayed.

id: abcde and name: pabbly

Pattern Matched Routes

You can also use  regex  to restrict URL parameter matching. Suppose you need an id which a 4-digit number. You can use the following route definition :

var express = require('express');
var app = express();

app.get('/things/:id([0-9]{4})', function(req, res){
   res.send('id: ' + req.params.id);
});

app.listen(2000);

Note that this will only match the requests that have a 4-digit long id. You can use more complex regex to match/validate your routes. If none of your routes match the request, you’ll get a “Cannot GET ” message as a response.

var express = require('express');
var app = express();

//Other routes here
app.get('*', function(req, res){
    res.send('Sorry, this is wrong URL.');
});

app.listen(2000);

For example, if we code the exact routes as above, on requesting a valid URL, the following output is displayed.

url:
localhost:2000/things/1234
output: id:1234

The following output is displayed, for a wrong URL request:

url:localhost:2000/things/123

Output: sorry, this is wrong URL.

Learn More: