Total.js Platform
Total.js Platform

Total.js Platform news and tutorials

Tutorial series - #2 Routing

Tutorial series - #2 Routing

Routes enable the outside world to communicate with your application using URLs. All routes are usually stored in a controller file. We declare our routes in the controller’s exports.install, which will be executed automatically only once the application starts. Inside we can start typing our routes.

The first argument in our route string is the HTTP request method. In this case, we used GET method followed by the route path and action function for handling our route. Both declarations are equivalent, but we recommend using the reference to the function instead of declaring it directly for readability and better orientation in your code.

NOTE: Make sure to NOT use ES6’s arrow functions. They won't work in this case because arrow functions don't support contexts.

Dynamic parameters

Dynamics parameters are defined inside {}. You can define multiple parameters in a single route.

In our case, the dynamic parameter is userid. We can access it with this.params.userid in our action function or use the shorthand this.id, which is always a reference to the FIRST parameter route - userid in our case.

Query parameters

To access query strings you can use this.query object to access all query values:

  • Request: https://localhost:8000/greeting?name=Total
  • Response: "Hello, Total"
NOTE: All received query values are strings, even if you send number, you need to parse it first with String.parseInt() or add + symbol before your value: +"123" will return 123.

Sending arrays in query string

If you want to receive an array from your query string, you can create your own protocol of sending and receiving arrays. For example, you can join(‘-’) your array before sending to create a single string, and after receiving that string simply split(‘-’) that string to get a parsed array with your values.

Wildcards

To define wildcards in your route simply add * at the end of your path. You can use a wildcard to direct every path of your app to an action or a single view:

Learn more about Total.js view engine

Others

Adding and removing routes dynamically

In some cases, you want to add or remove your routes dynamically while your app already runs. To add a new route you can use again global function ROUTE() anywhere in your code. If you want to remove an already existing route, there are two ways to do it:

  1. Using ROUTE('GET /admin/', null) to remove GET /admin/ route.
  2. ROUTE() function returns a route instance that contains the remove method so you can assign a route instance to a variable when creating a route and later call the remove method in that variable.

Both ways are valid, but in most cases, you are not assigning every route instance in a variable, so the first method is more practical to use.