Chapter 5. Routing

 

This chapter covers

  • Simple and pattern-matching routing
  • Using middleware with routing
  • Serving static files with express.static, Express’s built-in static file middleware
  • Using Express with Node’s built-in HTTPS module

As you’ve seen, routing is one of Express’s big features, allowing you to map different requests to different request handlers. In this chapter, we’ll go far more in depth. We’ll look at routing in detail, show how to use Express with HTTPS, explore Express 4’s new routers features, and more. We’ll also build a couple of routing-centric applications, one of which will be a running example throughout the remainder of the book.

In this chapter, I’ll tell you everything there is to know about routing in Express.

5.1. What is routing?

Let’s imagine you’re building the homepage for Olivia Example. She’s a great lady and you’re honored to build her website.

If you’re using a browser to visit example.com/olivia, here’s what the first part of the raw HTTP request might look like:

GET /olivia http/1.1

That HTTP request has a verb (GET), a URI (/olivia), and the HTTP version (1.1). When you’re routing, you take the pair consisting of the verb and the URI and map it to a request handler. You basically say, “Hey, Express! When you see a GET request to /about_me, run this code. And when you see a POST request to /new_user, run this other code.”

That’s pretty much it—routing maps verbs and URIs to specific code. Let’s look at a simple example.

5.2. The features of routing

5.3. Using routers to split up your app

5.4. Serving static files

5.5. Using Express with HTTPS

5.6. Putting it all together: a simple routing demo

5.7. Summary