Advanced Routing Using Express: Node.js


After learning basics of routing, lets look at some of the advances/complex routing techniques of Express.

routes node server request response technotip Basic Routing Using Express: Node.js

In this video tutorial, we shall teach you how to work with multiple params and also defining routes with regular expressions.

Two params in a Route: Express
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var companies = [
   {
      "name": "Apple",
      "product": "iPhone"
   },
   {
      "name": "Google",
      "product": "Nexus"
   },
   {
      "name": "Oracle",
      "product": "sql"
   },
   {
      "name": "Microsoft",
      "product": "Windows"
   }
 ];
 
app.get('/user/:from-:to', function(req, res){
    var from = parseInt(req.params.from, 10),
        to   = parseInt(req.params.to,   10);
 
  res.json( companies.slice(from, to+1) );
});

Here we have an array of objects – which in real-time application we get from a database ( Ex: MongoDB ). Now we define a route, and get two params in a single URL. By fetching and parsing those two params, we pass it to slice method of array and get array objects within the range/limit. Also note the use of response in json formatting while sending the data using response object.

Regular Expressions in Routes: Express
app.js

1
2
3
4
5
6
7
8
9
app.get(/\/user\/(\d*)\/?(edit)?/, function(req, res){
 
if(req.params[0])
 res.send("Viewing user id: "+req.params[0]); 
else if(req.params[1])
 res.send("editing user with an id "+req.params[0]);
else
 res.send("Enter User ID!!");
});

we enter our regular expression between two forward slashes. And to escape the forward slash present inside our regular expression, we make use of escape character i.e., a back slash. After /user/ we can have zero or more digits, after that an optional edit keyword followed by an optional trailing forward slash.

These routes match our pattern:
/user/
/user/userId/
/user/userId/edit
/user/userId/edit/

Depending on which URL the user is requesting, we could serve the purpose, using conditionals.

Advanced Routing Using Express: Node.js


[youtube https://www.youtube.com/watch?v=jYqhlVYnr30]

YouTube Link: https://www.youtube.com/watch?v=jYqhlVYnr30 [Watch the Video In Full Screen.]



Note: In our example we are simply displaying the view and edit modes. But in real-time applications you could replace it with some database queries and make sure the operations makes proper sense.

One thought on “Advanced Routing Using Express: Node.js”

  1. Array Object Properties

    PropertyDescription
    constructorReturns the function that created the Array object’s prototype
    lengthSets or returns the number of elements in an array
    prototypeAllows you to add properties and methods to an Array object

    Array Object Methods

    MethodDescription
    concat()Joins two or more arrays, and returns a copy of the joined arrays
    indexOf()Search the array for an element and returns its position
    join()Joins all elements of an array into a string
    lastIndexOf()Search the array for an element, starting at the end, and returns its position
    pop()Removes the last element of an array, and returns that element
    push()Adds new elements to the end of an array, and returns the new length
    reverse()Reverses the order of the elements in an array
    shift()Removes the first element of an array, and returns that element
    slice()Selects a part of an array, and returns the new array
    sort()Sorts the elements of an array
    splice()Adds/Removes elements from an array
    toString()Converts an array to a string, and returns the result
    unshift()Adds new elements to the beginning of an array, and returns the new length
    valueOf()Returns the primitive value of an array

Leave a Reply

Your email address will not be published. Required fields are marked *