Fun with Routes

The following snippet illustrates the most simple route definition possible. Express translates the path strings to regular expressions, used internally to match incoming requests. Query strings are not considered when peforming these matches, for example GET / would match the following route, as would GET /?name=tobi.

source

Lets get into setting up some routes. In the app.js file the following line is how this comes together:

  1. var routes = require('./routes/index');

What’s happening here? Basically, Express is setting the var of routes to require the path and file of ./routes.index.

This var is then used to set the root path of the app

  1. app.use('/', routes);

Using the res.send() we can do fun things like even send in JSON objects.

  1. });

This method allows us to then keep all our routes in the index.js file if needed. There are better ways to address a more complicated routing solution, but for the scope of this workshop, this is great.

Looking at our index.js file you should see the following:

  1. var express = require('express');
  2. var router = express.Router();
  3. /* GET home page. */
  4. router.get('/', function(req, res) {
  5. });
  6. module.exports = router;
router.get

This is the function that will ‘get’ the URL path of /. Then we need to create a function that will make a (request) and res (response). The is another concept of next for chaining events would go here as well, but not shown in this example.

What is module.exports?

This is the object that’s actually returned as the result of a require call. This is a Node feature, more on this at .

Keep in mind that the value of the URL, /app, does not need to be the same value of the file itself. If the name of the view was foo.jade we could do the following:

  1. router.get('/app', function(req, res) {
  2. res.render('foo', { title: 'Express' });
  3. });

What’s interesting about this is that the route function is containing logic. Inside the route is a res.render function:

  1. res.render('foo', { title: 'Express' });

In the view template we see this:

These are two examples of how we can pull data from the ‘controller/route’ and display in the view. In this example we get the HTML output of:

  1. <p>Welcome to Express</p>

All of this seems to be a bleed of concerns as the route may also contain controller info? This is true and there is a movement in the community to change the name of the dir from routes to controllers.

But for the sake of this workshop and consistency, we will keep the current convention.