Node.js: routing in ExpressJS: the basics

Node.js: routing in ExpressJS: the basics

ExpressJS provides us with a series of enhancements for handling HTTP routing in Node.js.

ExpressJS provides us with a series of enhancements for handling HTTP routing in Node.js.

Let's say we want to handle a route like /topics. In Express we can write:

'use strict';
const app = require('express')();
app.get('/topics', (req, res) => {
});
app.listen(3000);

Now we want to handle a child path like /topics/nodejs. Instead of adding another literal path, we can use parameters:

app.get('/topics/:topic', (req, res) => {
   console.log(req.params.topic); // 'nodejs'
});

What happens now to the simple /topics route? In order to make it work without its child path, we need to make our parameter optional by using a powerful feature of ExpressJS: regular expressions.

app.get('/topics/:topic?', (req, res) => {
   if(req.params.topic) {
      console.log(req.params.topic); // 'nodejs'
   } else {
       console.log('Topics');
   } 
});

The topic parameter now has been made optional thanks to the ? modifier of regular expressions. In ExpressJS, regular expressions allow us to gain a more powerful control over routes by using complete regular expression patterns. Suppose we want to add an optional language parameter to our routes, such as /path/it. Our parameter must be made only of letters and a dash with a maximum length of 5 characters and a minimum length of 2.

app.get('/path/:lang([a-z-]{2,5})?', (req, res) => {

});

As we did earlier, this parameter is optional but if we try to pass a trailing number to our route, it simply won't work. The regular expression used here formally validates our path, thus making impossible to deviate from the routing specifications we defined above.

To summarize: in order to get the most interesting results from ExpressJS routing we need to experiment a little bit more with JavaScript regular expressions.