About this documentation node js v5 3

Page 184

Route Paths and Regular Expressions When you specify a path (like /foo) in your route, it’s eventually converted to a regular expression by Express. Some regular expression metacharacters are available in route paths: +, ?, *, (, and ). Let’s look at a couple of examples. Let’s say you want the URLs /user and /username to be handled by the same route: app.get('/user(name)?', function(req,res){ res.render('user'); });

One of my favorite novelty websites is http://khaaan.com. Go ahead: I’ll wait while you visit it. Feel better? Good. Let’s say we want to make our own “KHAAAAAAAAN” page, but we don’t want our users to have to remember if it’s 2 a’s or 3 or 10. The following will get the job done: app.get('/khaa+n', function(req,res){ res.render('khaaan'); });

Not all normal regex metacharacters have meaning in route paths, though—only the ones listed earlier. This is important, because periods, which are normally a regex met‐ acharacter meaning “any character,” can be used in routes unescaped. Lastly, if you really need the full power of regular expressions for your route, that is supported: app.get(/crazy|mad(ness)?|lunacy/, function(req,res){ res.render('madness'); });

I have yet to find a good reason for using regex metacharacters in my route paths, much less full regexes, but it’s good to know the functionality is there.

Route Parameters Where regex routes may find little day-to-day use in your Expression toolbox, you’ll most likely be using route parameters quite frequently. In short, it’s a way to make part of your route into a variable parameter. Let’s say in our website we want to have a page for each staff member. We have a database of staff members with bios and pictures. As our company grows, it becomes more and more unwieldy to add a new route for each staff member. Let’s see how route parameters can help us: var staff = { mitch: { bio: 'Mitch is the man to have at your back in a bar fight.' }, madeline: { bio: 'Madeline is our Oregon expert.' }, walt: { bio: 'Walt is our Oregon Coast expert.' }, };

162

| Chapter 14: Routing

www.it-ebooks.info


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.