Implementing the router

Almost every web application needs a router, which is a component that acts as a front door and accepts the incoming queries. It analyzes the parameters of the request and decides which module of our system will serve the result.

We are using JavaScript language in the backend (via Node.js) and frontend (interpreted by the web browser). In this section, we will write a router that works in both the sides of our application. Let's start examining what the Node.js part needs:

// frontend/js/lib/Router.js
module.exports = function() {
  return {
    routes: [],
    add: function(path, handler) {
      // ...
    },
    check: function(fragment, params) {
      // ...
    }
  }
};

Router.js exports two methods. The first one registers routes by accepting a path ...

Get Node.js By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.