Routes.js
Routes.js is a small JavaScript library that provides browser routing for JavaScript applications using HTML5 pushState and/or hash routing.
Usage
Basic
To use Routes.js in your browserify or webpack web app install using npm.
npm install routes-js
And to use Routes.js in your app:
var router = ; router; router; router;
API
Options
When creating a router options may be passed in the form of an object hash to customize your router.
use
Use to force your router to use hash-based routing by setting it tohash
.
A router will use History.pushState by default,
falling back to hash-based routing (using the URL hash as in index.html#/my/path
) when the browser does not support
pushState
. Your web server needs to be able to deliver your app's HTML at any URL the application uses. If your server
does not handle this (e.g. if it is hosted from a static file server) you should set your router to use hash-based
routing.
// a prefix isn't needed in hash-based routingvar router = ; // pushState routingvar router = ;
Hosting the App Somewhere Other Than the Root
Often an application is not hosted at the root URL of a page. When this is the case you don't want to have to use the
full path in your routes. You can easily solve this by putting the root of your app in a <base>
element on your page.
For example, if your app exists at http://example.com/mortgage/calculator/
then you would add a base element like the
following to your app HTML page.
A route of /
would go to http://example.com/mortgage/calculator/
while a route of /step2
would go to
http://example.com/mortgage/calculator/step2
. Note that this is not needed for hash-based routing.
Routes
Routes can be strings or regular expressions. They match on URL paths and call an associated callback when the URL
matches. String routes can contain params (/:paramName
) and wildcard endings (/*
). The callbacks are called with two
arguments, a request object and a function to pass control to the next route if desired.
The request object (usually shorted to req
) contains the URL and path strings, and params and query objects, with all
the info.
Here are some examples.
Using params:
router; router;
Using passthrough routes to load data or check for login status:
// Define first so that we don't get into a redirect looprouter; router; router;
Using wildcard endings:
router;
Using regular expressions:
router;
Param
You may register a function to run before any routes that have a matching parameter using routeer.param
. This can be
used to set or load data.
router; router;
In addition, you can pass a regular expression into param
to enforce the parameter matches before the route will
match.
router; router; router;