Routing

Routing refers to how an application’s endpoints (URIs) respond to client requests.

You define routing using methods of the Express app object that correspond to HTTP methods; for example, app.get() to handle GET requests and app.post to handle POST requests.

You can also use app.all() to handle all HTTP methods and app.use() to specify middleware as the callback function

These routing methods specify a callback function (sometimes called “handler functions”) called when the application receives a request to the specified route (endpoint) and HTTP method. In other words, the application “listens” for requests that match the specified route(s) and method(s), and when it detects a match, it calls the specified callback function.

In fact, the routing methods can have more than one callback function as arguments. With multiple callback functions, it is important to provide next as an argument to the callback function and then call next() within the body of the function to hand off control to the next callback.

Basic routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.

  • Route definition takes the following structure:
  • app.METHOD(PATH, HANDLER)
  • Where
    • app is an instance of express.
    • METHOD is an HTTP request method, in lowercase.
    • PATH is a path on the server.
    • HANDLER is the function executed when the route is matched.
  • The following examples illustrate defining simple routes.Respond with Hello World! on the homepage:

    1
    2
    3
    app.get('/', function (req, res) {
    res.send('Hello World!')
    })
  • Respond to POST request on the root route (/), the application’s home page:

    1
    2
    3
    app.post('/', function (req, res) {
    res.send('Got a POST request')
    })
  • Respond to a PUT request to the /user route:

    1
    2
    3
    app.put('/user', function (req, res) {
    res.send('Got a PUT request at /user')
    })
  • Respond to a DELETE request to the /user route:

    1
    2
    3
    app.delete('/user', function (req, res) {
    res.send('Got a DELETE request at /user')
    })

Route methods

  • A route method is derived from one of the HTTP methods, and is attached to an instance of the express class.

  • Express supports methods that correspond to all HTTP request methods: get, post, and so on.

  • There is a special routing method, app.all(), used to load middleware functions at a path for all HTTP request methods. For example, the following handler is executed for requests to the route “/secret” whether using GET, POST, PUT, DELETE, or any other HTTP request method supported in the http module.

  • The following code is an example of routes that are defined for the GET and the POST methods to the root of the app.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // GET method route
    app.get('/', function (req, res) {
    res.send('GET request to the homepage')
    })

    // POST method route
    app.post('/', function (req, res) {
    res.send('POST request to the homepage')
    })

Route paths

Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.

The characters ?, +, *, and () are subsets of their regular expression counterparts. The hyphen (-) and the dot (.) are interpreted literally by string-based paths.

If you need to use the dollar character ($) in a path string, enclose it escaped within ([ and ]). For example, the path string for requests at “/data/$book”, would be “/data/([\$])book”.

  • Here are some examples of route paths based on strings.

    • This route path will match requests to the root route, /.

      1
      2
      3
      app.get('/', function (req, res) {
      res.send('root')
      })
    • This route path will match requests to /about.

      1
      2
      3
      app.get('/about', function (req, res) {
      res.send('about')
      })
    • This route path will match requests to /random.text.

      1
      2
      3
      app.get('/random.text', function (req, res) {
      res.send('random.text')
      })
  • Here are some examples of route paths based on string patterns.

    • This route path will match acd and abcd.

      1
      2
      3
      app.get('/ab?cd', function (req, res) {
      res.send('ab?cd')
      })
    • This route path will match abcd, abbcd, abbbcd, and so on.

      1
      2
      3
      app.get('/ab+cd', function (req, res) {
      res.send('ab+cd')
      })
    • This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on.

      1
      2
      3
      app.get('/ab*cd', function (req, res) {
      res.send('ab*cd')
      })
    • This route path will match /abe and /abcde.

      1
      2
      3
      app.get('/ab(cd)?e', function (req, res) {
      res.send('ab(cd)?e')
      })
  • Examples of route paths based on regular expressions:

    • This route path will match anything with an “a” in it.

      1
      2
      3
      app.get(/a/, function (req, res) {
      res.send('/a/')
      })
    • This route path will match butterfly and dragonfly, but not butterflyman, dragonflyman, and so on.

      1
      2
      3
      app.get(/.*fly$/, function (req, res) {
      res.send('/.*fly$/')
      })

Route parameters

  • Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
    1
    2
    3
    Route path: /users/:userId/books/:bookId
    Request URL: http://localhost:3000/users/34/books/8989
    req.params: { "userId": "34", "bookId": "8989" }
  • To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
    1
    2
    3
    app.get('/users/:userId/books/:bookId', function (req, res) {
    res.send(req.params)
    })

Route handlers

  • You can provide multiple callback functions that behave like middleware to handle a request. The only exception is that these callbacks might invoke next(‘route’) to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.

  • Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.

    • A single callback function can handle a route. For example:

      1
      2
      3
      app.get('/example/a', function (req, res) {
      res.send('Hello from A!')
      })
    • More than one callback function can handle a route (make sure you specify the next object). For example:

      1
      2
      3
      4
      5
      6
      app.get('/example/b', function (req, res, next) {
      console.log('the response will be sent by the next function ...')
      next()
      }, function (req, res) {
      res.send('Hello from B!')
      })
    • An array of callback functions can handle a route. For example:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      var cb0 = function (req, res, next) {
      console.log('CB0')
      next()
      }

      var cb1 = function (req, res, next) {
      console.log('CB1')
      next()
      }

      var cb2 = function (req, res) {
      res.send('Hello from C!')
      }

      app.get('/example/c', [cb0, cb1, cb2])
    • A combination of independent functions and arrays of functions can handle a route. For example:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      var cb0 = function (req, res, next) {
      console.log('CB0')
      next()
      }

      var cb1 = function (req, res, next) {
      console.log('CB1')
      next()
      }

      app.get('/example/d', [cb0, cb1], function (req, res, next) {
      console.log('the response will be sent by the next function ...')
      next()
      }, function (req, res) {
      res.send('Hello from D!')
      })

Response methods

  • The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
Method Description
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.
res.redirect() Redirect a request.
res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its string representation as the response body.

app.route()

  • You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos.

  • Here is an example of chained route handlers that are defined by using app.route().

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    app.route('/book')
    .get(function (req, res) {
    res.send('Get a random book')
    })
    .post(function (req, res) {
    res.send('Add a book')
    })
    .put(function (req, res) {
    res.send('Update the book')
    })

express.Router

  • Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.

  • The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app.

  • Create a router file named birds.js in the app directory, with the following content:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    var express = require('express')
    var router = express.Router()

    // middleware that is specific to this router
    router.use(function timeLog (req, res, next) {
    console.log('Time: ', Date.now())
    next()
    })
    // define the home page route
    router.get('/', function (req, res) {
    res.send('Birds home page')
    })
    // define the about route
    router.get('/about', function (req, res) {
    res.send('About birds')
    })

    module.exports = router
  • Then, load the router module in the app:

    1
    2
    3
    4
    5
    var birds = require('./birds')

    // ...

    app.use('/birds', birds)
  • The app will now be able to handle requests to /birds and /birds/about, as well as call the timeLog middleware function that is specific to the route.